- Home /
Bullet going in direction of moving object
So i have a script in C# for firing bullets and moving object tagged as "Target" from one side to another. I can't figure out how to change it so when i click, the bullets go to in my Target direction. I don't want bullet to follow this obejct. Just fire where it was when i clicked mouse button. I'm pretty newbie in coding.
using UnityEngine;
using System.Collections;
public class Shooting : MonoBehaviour
{
public Rigidbody2D projectile;
public float speed = 20;
Transform Target;
void start() {
GameObject target_go = GameObject.FindGameObjectWithTag("Target");
}
void Update ()
{
if (Input.GetMouseButtonDown(0))
{
Rigidbody2D instantiatedProjectile = Instantiate(projectile,transform.position,transform.rotation)as Rigidbody2D;
instantiatedProjectile.velocity = transform.TransformDirection(new Vector3(0, 0,speed));
}
}
}
Answer by robertbu · May 06, 2014 at 11:54 PM
I made two significant changes here. First take a look how I initialized 'target' in Start(). Note this change will cause a null reference exception if a game object with a name of "Target" does not exist in the scene. If that is a possibility, you need to check the result of the GameObject.Find() before getting the transform. Second, take a look at how I calculated the velocity.
using UnityEngine;
using System.Collections;
public class Shooting : MonoBehaviour
{
public Rigidbody2D projectile;
public float speed = 20;
Transform target;
void start() {
target = GameObject.FindGameObjectWithTag("Target").transform;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Rigidbody2D instantiatedProjectile = Instantiate(projectile,transform.position,transform.rotation)as Rigidbody2D;
instantiatedProjectile.velocity = (target.position - transform.position).normalized * speed;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613144415im_/https://answers.unity.com/themes/thub/images/avi.jpg)