Solved! Car movement c# Unity 2017

Yo guys,

I am working on a basic movement script for a car but i get some problems with my input.

I want a basic force that put my car foward and when i use my horizontal input it move 1 unity to the left to right.

If someone can help me it would be super .

What did i do wrong and how can i do it better in the future.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Car_Move : MonoBehaviour {
    public float thrust;
    public Rigidbody rb;
    public float speed;


    // Use this for initialization
    void Start () {
       
        rb = GetComponent<Rigidbody>();
    }
   
    // Update is called once per frame
    void FixedUpdate ()

    {
        Controll ();
            rb.AddForce (speed * -6, 0, 0);
        }


    void Controll (){
   

        if (Input.GetAxis ("Horizontal") > 0) {
            rb.AddForce (0, 0, 20f);
            Debug.Log ("right");
        } else {
            if (Input.GetAxis ("Horizontal") > -1) {
                rb.AddForce (0, 0, -20f);
                Debug.Log ("left");
            }
        else {
                rb.AddForce (speed * -6, 0, 0);

            }
        }
    }
}

Thanks,

Casper

2 Likes

Hi Casper,

I may have found an issue on your script but I hope i read it right !

You are actually checking if the Horizontal axis is superior than -1 to turn left, what means that from -0.99 to 0 you’d turn left but on -1 your car won’t turn and will only get a forward force applied.

What you can write is something like :

if (Input.GetAxis ("Horizontal") > 0) {
    // Turn right
} else if (Input.GetAxis ("Horizontal") < 0) {
    // Turn left 
}
// If Horizontal == 0 : do nothing because you already apply a forward force in FixedUpdate()

I didn’t check my code sorry. Tell me if anything get wrong :slight_smile:

I’m not used to implement the GetAxis method because I only work on mobile but I heard that implementing a deadzone when you work with joysticks is a good practice so I made a quick search on google and I found this : Casino software guide everything you need to know - Third Helix
Maybe you should read it to learn more about all this !

Cheers

1 Like

Thanks Stalker,

It did the job!!! :slight_smile:

You are right becaus i had it on >-1 it was always adding force

Now it fixed :slight_smile:
Great job Thanks

1 Like