unity-game-engineonmousedown

Unity 2D - Tap Image to accelerate car


I am making a Hill Climb Racing clone as a school project. Currently my car is accelerating with the A and D keys in my editor (movement = Input.GetAxis("Horizontal");), however the game has to be for Android, therefore like in the OG game, I added 2 sprites for brakes and pedals and added EventSystems to them eg.:

public void OnPointerDown(PointerEventData eventData)
{
    gas.sprite = OnSprite_gas;
    is_clicking = true;

}

and I dont know how to change acceleration to when the gas image is clicked and held down and how to brake (but not go backwards) when the brake is held down.


Solution

  • You seem to be on the right track.

    In the car's Update() method, you will want to check if the brake or accelerator button is_clicking property is set, and handle the movement force. This could look something like:

    void Update()
    {
        if (accelerator.is_clicking)
        {
            movement = new Vector3(1f, 0f, 0f) * speed;
        }
        else if (brake.is_clicking)
        {
            movement = new Vector3(-1f, 0f, 0f) * speed;
        }
        else
        {
            movement = new Vector3(0f, 0f, 0f);
        }
    }
    
    void FixedUpdate()
    {
        rb.AddForce(movement * Time.fixedDeltaTime);
    }
    

    You could then check if the velocity is close to 0 to stop applying the brake force.