- Home /
Shooting a projectile forward in 3d space
If I have a cube facing a random direction, how can I make it shoot a projectile in it's "forward" direction?
Do you want to fire it like a projectile using Unity physics, so that it travels up in an arc, falls, maybe bounces? Or do you want the projectile to move in a straight line, more like an arcade game might do it?
Answer by Jaap Kreijkamp · Feb 02, 2010 at 02:21 AM
Basically, just instantiate the bullet with the same rotation as the cube:
var spawnDistance : float = 1.0f; // don't want the bullet spawn in centre
// ...
GameObject.Instatiate(prefab, transform.position + spawnDistance * transform.forward, transform.rotation);
// ...
and let the bullet move itself in the transform.forward direction:
var speed : float = 2.0;
function Update() { transform.position += Time.deltaTime speed transform.forward; }
or if you're using a rigidbody as bullet:
var force : float = 20.0f;
function Start() { rigidbody.AddForce(transform.forward * force); }
Answer by Eduardo Meade · Feb 02, 2010 at 02:59 AM
you can use transformdirection, which ensures that the projectile will have a correct direction in wordl coordinates ( in case the object that instantiates your projectile is not a "root" object )
some code:
var newProjectile = Instantiate( projectile, transform.position, transform.rotation );
newProjectile.velocity = transform.TransformDirection( Vector3( 0, 0, speed) );
we are using Vector3( 0, 0, speed ) because in Unity the default forward axis is Z
Answer by Qamar · Dec 01, 2010 at 07:57 AM
For the Projectile you can use following:
var projectile: GameObject; var force: float;
function Update(){ if(Input.GetMouseButtonDown(0)){ projectile.rigidbody.AddForce(projectile.transform.forward projectile.rigidbody.mass force, ForceMode.Impulse);
}
}
this will Add an immidiate force to the object to forward.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
When dragging a Door open using RIGIDBODYSCRIPT Plays sound. 1 Answer
Determine Area using code 1 Answer
How to keep physics consistent? 1 Answer
constant force 1 Answer