- Home /
transform.forward problem
I am working on a tower defense game involving a tower shooting an enemy, but when the tower shoots, it shoots the bullet forward in the world direction instead of on its rotation. The bullet doesn't go forward towards the enemy but goes forward in world space off screen.
I am using the following code to shoot the bullet from the tower script,
var ball = Instantiate(bullet, spawnPoint.transform.position, transform.localRotation);
ball.rigidbody.AddForce(ball.transform.localPosition.forward * 5000);
bullet is a GameoObject spawnPoint is a Transform
Is there a new way to shoot something on its local forward axis? Was the .forward script changed recently, because most of the gun scripts are using it but it doesn't work for me now. How do I fix the problem and shoot it forward.
Answer by aldonaletto · Nov 27, 2013 at 02:53 AM
transform.localPosition.forward ? This makes no sense, or will result in Vector3.forward. You should simply use transform.forward instead:
ball.rigidbody.AddForce(ball.transform.forward * 5000);
already tried transform.forward, used localposition hoping it would solve the problem. is there a way to send the rotation of the tower to the ball? I think the ball isn't taking in the rotation from the instantiate line. Sorry to change the problem type.
There's another error: you should pass spawnPoint.transform.rotation to Instantiate, not transform.localRotation - change the code like this:
var ball = Instantiate(bullet, spawnPoint.transform.position, spawnPoint.transform.rotation);
Answer by rutter · Nov 27, 2013 at 02:58 AM
This line:
ball.rigidbody.AddForce(ball.transform.localPosition.forward * 5000);
ball.transform.localPosition
represents the ball's position, not the direction it's facing, so I'm not sure what "forward" is relative to that. To be honest, I'm surprised that compiles.
You probably mean ball.transform.forward
, which uses the ball's rotation.
tried transform.forward already, hoped the localposition would send it in the right direction, is there a way to send the rotation to the ball from the tower?
It looks like this script is attached to the tower? If so, transform.forward
is the tower's forward direction. If not, you'll need a reference to the tower, and from there you can get its transform.
GOT IT, changed transform.position to spawnPoint.transform.position, because it was already facing in the correct direction. Thank you for the help.
Your answer
Follow this Question
Related Questions
Physics in 2D mode not working? 0 Answers
ForceMode.VelocityChange vs. simply adding to .velocity 0 Answers
Basic Jump Pad help 2 Answers
rb.addforce being really buggy 2 Answers
Gameobject going past target when using rigidbody2d.addforce 1 Answer