0
votes

I am using Unity2D for a simple car / bike physics game. I want when i press the right or left arrow, the wheel sprite to rotate, so the car is moving.

This is my code:

float move=Input.GetAxis("Horizontal");
        if (Input.GetKey(KeyCode.RightArrow))
        {

            rigidbody2D.velocity = new Vector2(move*10,rigidbody2D.velocity.y);


        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {


            rigidbody2D.velocity = new Vector2(move * 10, rigidbody2D.velocity.y);

        }

But this is just 'pushing' the wheel, is not rotating, and if the car is in the air you can still move it...I need to rotate the wheel, not push it. Can anyone help?

2

2 Answers

1
votes

velocity is simply moving in a direction, like what you are seeing in your script. angularVelocity on the other hand is rotation. Try playing with the rigidbody2D.angularVelocity and see what happens.

0
votes

This simple code will spin the 2d object. The speed of the spin depends on how fast a chosen object's velocity is.

#pragma strict

var power : float; //the engine power applied to the wheel
var car : GameObject; //the object whose velocity you are calculating

function Start () {

}

function Update () {

 var wheelpower = car.rigidbody2D.velocity.x * power; //velocity of "car" * engine power

if(Input.GetKey(KeyCode.D)){
    transform.Rotate(0, 0, -wheelpower);}
if(Input.GetKey(KeyCode.A)){
    transform.Rotate(0, 0, wheelpower);}

}