Sign in to follow this  
CaioMGA

How to access parameters properly

Recommended Posts

Hi!

I can access the x parameter on this.draw() function, why it doesn't work on this.updateRotation()??
After I create a Shooting Module on my game loop I can access the getX().
What I am missing?

function ShootingModule(_canvas){
	this.x = 200;
	this.y = 500;
	this.radius = 16;
	this.rotation = 0;
	this.canvas = _canvas;
	this.color = "blue";
	this.draw = function (context){
		context.beginPath();
		context.translate(this.x, this.y);
		context.rotate(this.rotation * Math.PI / 180);
		context.arc(0, 0, this.radius, 0, Math.PI * 2, true);
		context.fillStyle = this.color;
		context.fill();
		context.fillRect(-6, -this.radius -6, 12, 12);
		context.stroke();
		context.setTransform(1, 0, 0, 1, 0, 0);
	};
	this.updateRotation = function(e){
		console.log(this.x);
		this.rotation = Math.atan2(e.clientY - this.y, e.clientX - this.x);
	};
	this.update = function(){

	};

	this.getX = function(){
		return this.x;
	};
}

In my main loop script:

playerShootingModule = new ShootingModule(canvas);
canvas.addEventListener('mousemove', playerShootingModule.updateRotation, true);

Share this post


Link to post
Share on other sites

Care must be taken when referencing "this" in a callback function because the value of "this" will likely not be the object you actually want when the callback is invoked. You can ensure the callback references the desired "this" object by using bind:

canvas.addEventListener('mousemove', playerShootingModule.updateRotation.bind(playerShootingModule), true);

 

Share this post


Link to post
Share on other sites
6 hours ago, BobF said:

Care must be taken when referencing "this" in a callback function because the value of "this" will likely not be the object you actually want when the callback is invoked. You can ensure the callback references the desired "this" object by using bind:


canvas.addEventListener('mousemove', playerShootingModule.updateRotation.bind(playerShootingModule), true);

 

I see.
Thanks a lot.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.