Simplexible
Simplexible

Reputation: 41

What's wrong with my Vehicle code?

I was trying to create a car in unity using a C# Script, everything seems to be fine, the car rotates left and right, except 1 problem. when I press the forward or backwards keys, the car moves left and right instead of forward and backwards, I can't see anything wrong with my code, here's my code:

using UnityEngine;
using System.Collections;

public class Car : MonoBehaviour {
    private Rigidbody carRigid;
    public int speed;
    public int rotateSpeed;

    // Use this for initialization
    void Start () {
        carRigid = GetComponent<Rigidbody> ();

    }

    // Update is called once per frame
    void Update () {

    }
    void FixedUpdate(){
        if (Input.GetButton("Forward")){
            carRigid.AddForce (transform.forward * speed * Time.deltaTime);
}
        if (Input.GetButton("Reverse")){
            carRigid.AddForce (transform.forward * -speed * Time.deltaTime);
        }

        if (Input.GetButton("Left")){
            transform.Rotate (0, rotateSpeed, 0);
        }

        if (Input.GetButton("Right")){
        transform.Rotate (0, rotateSpeed, 0);
        }
    }
}

Upvotes: 2

Views: 118

Answers (3)

Sebastian TY
Sebastian TY

Reputation: 26

Your car is moving on another axis which is different than the axis you want. try transform.right / transform.left or transform.up / transform.down .

Upvotes: 1

BlackBrain
BlackBrain

Reputation: 1029

Maybe it's because you have imported a 3D model which it's local forward is not correct.

You have some choices: 1) Fix it in the 3d modeling program an export it again.

2) Create an empty GameObject and make this the parent of your car. Assign the rigid body and relevant codes to this GameObject and Rotate the car model in it's local space until it's fixed ( 90 degrees I guess).

3) use transform.right or transform.left depending on the rotation of your model.

I personally prefer first choice.

Upvotes: 0

Tom
Tom

Reputation: 2472

I've just tested your code in a blank Unity scene, and I think you AddForce() is the culprit!

I used

if (Input.GetKey(KeyCode.W))
{
    transform.position += transform.forward * speed * Time.deltaTime;
}

and this seems to be working great!

Upvotes: 1

Related Questions