- Home /
Not understanding how rigidbody2D.AddForce works
I know this has been asked before but I'm not able to find any answer that's not too technical or vague for me (I'm really new to coding). I'm creating an Asteroids-like space shooter using Unity's 2D features, but I don't know how to make rigidbody2D.AddForce work to make the ship move forward using the W key. A clear "try this code" answer with an explanation would be tremendously appreciated. I had made the game in 3D and it works fine with this code:
#pragma strict
var thrust: int;
var rotationSpeed: float;
var thrustEmitter: ParticleEmitter;
function Update () {
if (Input.GetKey (KeyCode.A))
transform.Rotate(Vector3.left * Time.deltaTime * rotationSpeed);
if (Input.GetKey (KeyCode.D))
transform.Rotate(Vector3.right * Time.deltaTime * rotationSpeed);
if (Input.GetKey (KeyCode.W)){
thrustEmitter.emit=true;
rigidbody.AddForce(transform.forward*Time.deltaTime*thrust);
}
else{
thrustEmitter.emit=false;
}
}
When remaking the game in 2D, the rotation and particle emitter are working properly, but the ship's not moving forward. Here's the code I have right now for 2D (Thrust is set to 1000):
#pragma strict
var thrust: int;
var rotationSpeed: float;
var thrustEmitter: ParticleEmitter;
function Update () {
if (Input.GetKey (KeyCode.A))
transform.Rotate(Vector3.forward * Time.deltaTime * rotationSpeed);
if (Input.GetKey (KeyCode.D))
transform.Rotate(Vector3.back * Time.deltaTime * rotationSpeed);
if (Input.GetKey (KeyCode.W)){
thrustEmitter.emit=true;
rigidbody2D.AddForce(Vector2.up * thrust);
}
else{
thrustEmitter.emit=false;
}
}
Thanks!
I don't see any problem here. The top of your sprite is what you consider the 'forward' side? Is 'thrust' set to a high enough value in the Inspector? Is it not moving or moving in the wrong direction.
Hey robertbu. "forward" and "back" are the left and right of my sprite, respectively. 'thrust' is set at 1000 right now, setting it to 10000 or 100000 isn't changing anything. Right now the sprite isn't moving at all, only rotating with the A and D keys.
Just for debugings sake try to switch "Vector2.up" with "Vector3.one" or "new Vector3(1,1,1)" and check if it moves at all. If you have rotated your rocket in a wierd way the y axis may be in the depth and you are only moving the rocket away from the camera, but since it's a 2D game you won't see that. At this point though it should not move in the right direction.