- Home /
Question by
sunnykwong91500 · Jun 03, 2018 at 03:30 AM ·
2dgunmouse position
How come the bullet does not follow my mouse in Unity2D?
Hey guys, I'm trying to make a top down shooter and I am having a lot of trouble trying to get the bullet to shoot towards the mouse. This is my current code:
void PointTo()
{
Vector2 positionOnScreen = Camera.main.WorldToViewportPoint(transform.position);
Vector2 mouseOnScreen = Camera.main.ScreenToViewportPoint(Input.mousePosition);
float localX = mouseOnScreen.x - positionOnScreen.y;
float localY = mouseOnScreen.y - positionOnScreen.y;
//this finds the angle from -180 to 180 from the player to the mouse
float angleInRad = Mathf.Atan2(localY,localX);
//this finds the velocity of the X and Y if the mouse was limited to the circumference of a radius 1 circle
float speedY = Mathf.Sin(angleInRad);
float speedX = Mathf.Cos(angleInRad);
print("X = " + speedX * Mathf.Rad2Deg);
print("Y = " + speedY * Mathf.Rad2Deg);
rb2D.velocity = new Vector2(10*speedX, 10*speedY);
}
PointTo() is being called in start when the bullet is created. This sets the initial velocity of the bullet but it does not go towards my mouse. However it is always off by a little. I don't get what's wrong if I did the math wrong or not. Thanks in advance!
In the picture below the triangle is where the mouse is.
bullet-does-not-follow-mouse.png
(2.9 kB)
Comment