- Home /
Question by
SplitChicken · Sep 11, 2016 at 05:15 PM ·
2dinstantiatevelocitymouseposition
How to get bullet to fire at set velocity? [2D]
I figured out how to get the instantiated objects to travel to the mouse position, however the objects velocity is dependent on where the mouse is relative to the player (since it uses mousePos to add velocity)
using UnityEngine;
using System.Collections;
public class BulletController : MonoBehaviour {
public KeyCode shoot;
Vector2 mousePos;
public GameObject bullet;
Rigidbody2D rb;
public float speed;
GameObject instance;
// Update is called once per frame
void Update () {
if (Input.GetKey (shoot))
{
instance = (GameObject)Instantiate(bullet, new Vector3(transform.position.x, transform.position.y, transform.position.z + 1), Quaternion.identity);
rb = instance.GetComponent<Rigidbody2D> ();
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.x = mousePos.x - transform.position.x;
mousePos.y = mousePos.y - transform.position.y;
Debug.Log (mousePos);
rb.AddForce (mousePos * speed);
rb.gravityScale = 1f;
}
}
}
Is there a way I can have the instantiated object to move towards the mouse at a set velocity i.e. if the mouse was 1 pixel from the player, the instantiated object would move at the same speed as if the mouse were at 50 pixels from the player?
Comment
Best Answer
Answer by Cherno · Sep 11, 2016 at 05:36 PM
Normalize the mousePos Vector with Vector2.normalized or Vector2.Normalize.
Vector2 aimVector = mousePos.normalized;
rb.AddForce (aimVector * speed);