- Home /
c# 2D top down, fire projectale which continuously move in a direction
Hi, I am trying to fire a projectile that should move in a direction until it gets destroyed depending on mouse position.
The following code works but the bullet stops at where I clicked, how can I make this bullet continue on its path until destroyed?
public class BulletStats : MonoBehaviour
{
public int Damage = 1; // Damage inflicted
public bool isEnemyShot = false; // Projectile from player or enemies?
public Camera camera; // camera object
private float speed = 5f; // bullet speed
private Vector2 clickPos; // bullet direction
void Start()
{
camera = (Camera) GameObject.FindObjectOfType(typeof(Camera)); // get the camera
// get world location of click
clickPos = camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y));
Destroy(gameObject, 20); // give bullet 20 seconds lifetime
}
void Update()
{
// move the bullet in the right direction
transform.position = Vector2.MoveTowards(transform.position, clickPos, speed * Time.deltaTime);
}
}
Answer by Kiwasi · Jun 30, 2014 at 08:01 PM
What you need to do is convert the mouse position into a direction first.
Try the following:
// In the declarations
private Vector3 shotDirection;
// At line 15
shotDirection = (clickPos-transform.position).normalised;
// Replace line 22 with the following
transform.position = transform.position + shotDirection * speed * Time.deltaTime;
Answer by timvanderweijde · Jun 30, 2014 at 07:55 PM
Do you want the bullet move to the mouse position continuously? You should use the code:
clickPos = camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y));
also in the Update method.
Still, it will stop at the mouse position. What kind of behaviour do you want? Should it pass the mouse position when it's there?
Don't forget ScreenToWorldPoint is also using the z-as. Which won't work in 2D.
I added some extra lines in your code. (and from Bored$$anonymous$$ornmon)
var camPos = camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y)); clickPos = new Vector3 (camPos.x, camPos.y, 0); shotDirection = (clickPos-transform.position).normalized;
Answer by RakshithAnand · Jul 01, 2014 at 06:17 AM
What you need to do: Add a ridgidbody2D component to your bullet. make it isKinematic and fixed angle.
get direction by normalized method. (Like BoredMormon suggested)
void Update()
{
if(Input.GetMouseButtonUp(0))
{
// you get clickpos like what you have done and you do this
Vector3 shotDir = ((Vector3)clickPos - transform.position).normalized;
gameObject.rigidbody2D.velocity = shotDir;
}
}