Rotating player/weapons sprite's direction with mouse
-
Hi,
I've recently decided to transition from Love2D to Haxeflixel. I'm still an absolute beginner when it comes to programming so bear with me please. With the move to HaxeFlixel, I want to port over my little work in progress game that I was working on in Love2D where the the weapon (drawn separetly) aim is controlled with mouse courser position. If player moves their mouse over to the left side, the the player's sprite flips over to look at the mouse and vice versa, here's a little example:How could I implement this using flixel? I'm aware that flixel has a lot of functions built in to do this, rather than doing all the maths myself.
-
You could first make a
Vector2
pointing from the sprite to the mouse:var vectorToTarget:Vector2 = FlxG.mouse.getPosition() - this.getPosition(); // subtracting the target position vector from the entity's position vector gives us a vector pointing from us to the target
then, in the
update()
method, set the sprite's angle to the angle of the vector:this.angle = MathUtil.radToDeg(vectorToTarget.angle); // the Vector2's angle is in radians so we need to convert it to degrees
and check if the vector is pointing left or right, flipping the sprite accordingly:
if(vectorToTarget.x >= 0) { this.flipY = false; } else { this.flipY = true; }
You could also decide to use a
FlxVector
instead of aVector2
, in that case you'll need to use the method.subtract()
instead of just doing a subtraction operation when creating the vector, as theFlxVector
class doesn't overload the operators.
You also won't need to convert radians to degrees asFlxVector
measure their angle in degrees already inFlxVector.degrees
.Last thing to note:
I'm sure the code I've written here will need tweaking for your usecase, treat it as just a starting point, reply if you need more pointers.