Reputation: 1450
I'm trying to get my object to always face my player, but I'm struggling with the maths behind it. So far, my object does rotate wherever my player moves, but it's inconsistent.
This is what I use to rotate my object:
var targetX = player.x - this.width/2;
var targetY = player.y - this.height/2;
this.rotation = Math.atan2(targetY, targetX);
ctx.transform(1, 0, 0, 1, this.x, this.y);
//ART WORK
ctx.save()
ctx.translate(15, 15);
ctx.rotate(this.rotation);
ctx.fillStyle = "866c4a";
ctx.fillRect(-15, -15, this.width, this.height);
ctx.restore();
Like I said, it doesn't work correctly, and I believe it's to do with my maths.
Thanks
Upvotes: 0
Views: 937
Reputation: 1450
Well!!
I immediately found out what the issue was. I wasn't taking into account the objects position:
var targetX = player.x - this.x;
var targetY = player.y - this.y;
this.rotation = Math.atan2(targetY, targetX);
ctx.transform(1, 0, 0, 1, this.x, this.y);
//ART WORK
ctx.save()
ctx.translate(15, 15);
ctx.rotate(this.rotation);
ctx.fillStyle = "866c4a";
ctx.fillRect(-15, -15, this.width, this.height);
ctx.restore();
I'll leave this QnA up, incase someone else comes across this. :)
Upvotes: 1