Jump to content

How to access parameters properly


CaioMGA
 Share

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);
Link to comment
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);

 

Link to comment
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.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...