- Home /
Fire a Projectile towards a specific object?
I'm making a 2D Side Scroller and I'm trying to launch a projectile from an object called "StrawSpawn" towards and object called "Target" at a speed of 20.
With my current code my projectile always fires off to screen right at a slight angle and nearly too fast to see, regardless of where "StrawSpawn" and "Target" are located relative to each other.
Can someone take a look at my code and tell me what I'm doing wrong? Thanks.
var projectile : Rigidbody;
var speed = 20;
function Update ()
{
// Put this in your update function
if (Input.GetButtonDown("Fire")) {
// Instantiate the projectile at the position and rotation of this transform
var clone : Rigidbody;
clone = Instantiate(projectile, GameObject.Find("StrawSpawn").transform.position, transform.rotation);
clone.velocity = transform.TransformDirection (GameObject.Find("Target").transform.position * speed);
Destroy (clone.gameObject, 3);
}
}
Answer by MithosKuu · Sep 11, 2012 at 08:35 AM
After asking on the forums, this is the working code I ended up with for anyone else looking to do something similar:
var projectile : Rigidbody;
var speed = 20;
function Update ()
{
// Put this in your update function
if (Input.GetButtonDown("Fire")) {
// Instantiate the projectile at the position and rotation of this transform
var clone : Rigidbody;
clone = Instantiate(projectile, GameObject.Find("StrawSpawn").transform.position, transform.rotation);
clone.velocity = (GameObject.Find("Target").transform.position - transform.position).normalized * speed;
clone.velocity.y=0;
Destroy (clone.gameObject, 3);
}
}
Your answer
Follow this Question
Related Questions
Projectile move towards mouse cursor 3 Answers
2D Animation does not start 1 Answer
Shooting from Bone and twisting via bone 0 Answers
I shoot a projectile, but its rotation is wrong (c#) 1 Answer