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!
↧