I'm programming a game in Java, and I have what feels like a really, really newbie question, but I can't figure it out for the life of me. All I'm trying to do is set an object's rotation towards the mouse (which works fine), and then it receives an initial push in the direction it is rotated (towards the mouse).
The rotation appears to work fine, but the problem is that the movement is weird and off. I think a GIF would best explain it:
Yeah, I'm not sure what's going on. As you can see, the rotation is being set perfectly, but when the object moves, bad things happen. So I'll give the pieces of movement code I believe are relevant. This code is updated every tick (1/60th second)
dSpeed *= defaultFriction;
speed.x += (float)(dSpeed * Math.cos(rotation - 90));
speed.y += (float)(dSpeed * Math.sin(rotation - 90));
speed.x *= defaultFriction;
speed.y *= defaultFriction;
speed.x = Calculation.clamp(speed.x, -maxSpeed.x, maxSpeed.x);
speed.y = Calculation.clamp(speed.y, -maxSpeed.y, maxSpeed.y);
goalPos.x = pos.x + speed.x;
goalPos.y = pos.y + speed.y;
Then I basically do a while loop to move the object one pixel at a time using goalPos (to handle collisions easily) If anyone can help me, I'd really appreciate it, because I am really stuck. Thanks!
Your problem appears to be that you are passing rotation - 90 to Math.cos and Math.sin. However, as Math.cos and Math.sin use radians, you should use either rotation - Math.PI/2 or Math.toRadians(rotation - 90) depending on the units of your rotation variable.
Note that Math.asin, Math.acos, Math.atan, and Math.atan2 all return radians.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With