Question by
Miggarapo · May 02, 2016 at 11:05 PM ·
2dinstantiatevelocityaddforcemouseposition
Shot 2D Projectile in mouse direction always with same speed
Here is my code:
m_ShotCopy = Instantiate(m_Shot, transform.position, Quaternion.Euler(new Vector3(0, 0, 0))) as GameObject;
Rigidbody2D rigidBody = m_ShotCopy.GetComponent<Rigidbody2D>();
Vector3 m_ShootDirection;
m_ShootDirection = Input.mousePosition;
m_ShootDirection.z = 0.0f;
m_ShootDirection = Camera.main.ScreenToWorldPoint(m_ShootDirection);
m_ShootDirection = m_ShootDirection - transform.position;
//rigidBody.AddForce(new Vector2(m_ShootDirection.x * m_TurnSpeed, m_ShootDirection.y * m_TurnSpeed)); THIS OR VELOCITY
rigidBody.velocity = Vector3.MoveTowards(transform.position, m_ShootDirection, m_TurnSpeed);
DestroyShotCopy();
test.text = "x " + (p_rotation.m_MousePositionX).ToString();
test1.text = "y " + (p_rotation.m_MousePositionY).ToString();
m_Fired = true;
My player shoots from its position projectiles to the direction of the mouse position.
The problem is, the more far away the mouseposition from the player position is the faster the projectile gets. I want it just to shoot in mouse direction with always the same speed.
Feel free to correct my code or make a better one. The "AddForce" is commented. You can "un-commment" it and use it instead of "velocity". Both works fine, they just contain the same problem.
Comment
I've heard of .normalized but cant get it working with it.
Best Answer
Answer by Miggarapo · May 02, 2016 at 11:51 PM
Vector3 original = new Vector3(m_ShootDirection.x, m_ShootDirection.y); original = original.normalized;
thats the solution :)