Figure out velocity under an angle

Hello,

I am trying to achieve a shot being fired from a player under an angle.
The angle is determined by the mouse(if the mouse is in front and above the player then he will shoot at approximately 45 degrees)
I have figured out how to calculate the exact angle of the shot, but what I can’t figure out is how I can make that shot move towards where the mouse is located during firing.
This is all in 2d using Rigidbody2D.
Can someone help me?

Thanks.

There are several ways to go about this.
One is to just have the projectle look at the target coords. Then push it forward. I prefer this method as unity is essentially already doing this stuff.This is 3d though. In 2d, it’s a little different then this code. But the underlying concept is the same.

object.transform.lookat(target);
object.rigidbody2d.addforce(transform.forward * speed * modifier);

Since you’re 2d, this already answered question explains the details of how that works…

The other way is fetching world to screen co-ordinates with something like a raycast, and then using Pythagorean theorem to fetch the x,y of the projectile. The good thing about being in 2ds is I don’t know if you even have to use a ray or translation.

This is from a java site, I used it in one of java platform games. I did that instead of using the trig angles, as it wound up being a little cheaper. NitPicking cheap in unity is pointless though, so use whatever works easiest for you.

Both examples cover the underlying constructs, as well as providing easily portable code for the matter at hand.

this is specifically the part you’re wanting…This is platform java though, but as I said, like a four minute port…(in fact I just did it for ya…might not be 100%). Should get you started. The pythag, is the a^2 + b^2 = c^2. It’s from that, or the atan, or the vector3.forward that you can get the bullet moving.

var  deltaX :double = player.getX() - point.getX();
var  deltaY : double = player.getY() - point.getY();
var magnitude : double = Mathf.sqrt(deltaX*deltaX + deltaY*deltaY);

// It's possible for magnitude to be zero (cursor is over the person)
// Decide what you want the default direction to be to handle that case
var xVelocity :double = 1;
var yVelocity :double = 0;
if (magnitude != 0) 
   {
       xVelocity = deltaX / magnitude;
       yVelocity = deltaY / magnitude;
   }

//With the velocities computed when you first create the //bullet, at each tick you just need to use
 xPosition += xVelocity and yPosition += yVelocity.

Anyways, I hope this is what you were asking for. Good luck, and remember, this stuff takes time to learn, and unity has it’s own curve…