- Home /
How to create an Asteroids style moving in 2D mode?
I'm working on an asteroids style game, and I can't figure out how to apply a forward velocity for the ship. So far I've done is a rotation but any form of forward thrust I can't do.
This is my code so far:
public float speed = 10.0f;
public float rotationSpeed = 10.0f;
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.W))
{
//not working
rigidbody2D.AddForce(Vector2.up * speed);
}
float rotate = Input.GetAxis("Horizontal") * rotationSpeed;
transform.Rotate(0, 0, 0 - rotate);
}
Answer by marsfan · Sep 05, 2014 at 03:18 PM
For a start, use rigidbody2d.addrelativeforce as shown here: docs.unity3d.com/ScriptReference/Rigidbody2D.AddRelativeForce.html This will add force along the local axis. This will make setting the direction of force easier.
There's a compiler error saying:
Error 8 'UnityEngine.Rigidbody2D' does not contain a definition for 'AddRelativeForce' and no extension method 'AddRelativeForce' accepting a first argument of type 'UnityEngine.Rigidbody2D' could be found (are you missing a using directive or an assembly reference?) C:\Users\$$anonymous$$ark\Documents\Unity Projects\Swingship\Assets\playerScript.cs 87 25 Assembly-CSharp-vs
I've also tried Rigidbody2D.AddRelativeForce (With capital R). But nothing comes up in the VS intellisense.
How exactly did you call the AddRelativeForce? IIRC, it accepts a Vector2 plus the Force$$anonymous$$ode so it should look something like this:
this.rigidbody2D.AddRelativeForce(Vector2(x,y),Force$$anonymous$$ode2D.Force);
Since it's relative it will add x force along the object's local x-axis and y force on the local y-axis.
Sorry, for the late response. it seems that I have to use transform.up ins$$anonymous$$d of Vector2.up. Now the sprite is moving around. Thank you for answering, though. $$anonymous$$y new code is:
rigidbody2D.AddForce(transform.up * Time.deltaTime * speed * Input.GetAxis("Vertical") * 0.5f);
Answer by Multeezee · Aug 22, 2019 at 08:09 PM
This helped me find this: https://docs.unity3d.com/ScriptReference/Rigidbody2D-drag.html which helped me slow down a RigidBody Underwater. Thank you!