- Home /
Spawn bullet in front of object then apply force?
Hey there I can't seem to get my bullet to spawn in front of my player, then apply the force. I'm doing a top down space shooter but the object creates inside my ship and also doesn't go straight. It goes off to the left instead of forward. Here's my current code. Hope you guys can help.
var Bullet : Transform;
function Update ()
{
if(Input.GetButtonDown("Fire"))
{
Instantiate(Bullet,transform.position, Quaternion.identity);
Bullet.rigidbody.AddForce(transform.forward * 15);
}
}
The script is attached to my ship and runs off of it so I would assumed yet.
Try:
Bullet.rigidbody.AddRelativeForce(transform.forward * 15);
Should use the ships forward direction ins$$anonymous$$d of world space.
Also, you should use an offset from the position so its not at the center of the ship:
var offset : Vector3 = // use some offset values here
Instantiate(Bullet, transform.position + offset, ...
Instantiate(Bullet,new Vector2(transform.position.x,transform.position.y + distanceFromCenterOfShipToGun, Quaternion.identity);
add the distance from centre of ship to gun to the y position and it should offset to the right place and the Quaternion.identity should be set to the correct angle. Try transform.rotation in place of Quaternion.identity
Answer by Daphoeno · Mar 05, 2013 at 07:02 PM
var Projectile : Rigidbody;
var Spawn : Transform;
var Force : int = 1000;
function Start ()
{
gameObject.SetActiveRecursively(true);
}
function Update ()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
Toss();
}
}
function Toss()
{
gren = Instantiate(Projectile,Spawn.position,Spawn.rotation);
gren.rigidbody.AddForce(transform.forward * Force);
yield WaitForSeconds(0.2);
}
Your answer
Follow this Question
Related Questions
How to make my new Instances spawn in the right direction? 1 Answer
Shoot an object and have it move based on rotation 1 Answer
Can't make a bullet move in the direction the actor is facing 2 Answers
Problem with Shooting Accuracy 0 Answers
making bullet go travel at angle fired and limit gun rotation in Unity C# version 5.2 2D 1 Answer