Movimiento de coche en 2D

Después de estar un par de semanas ausentes intento. volver al Blog he intentaros enseñar nuevas cosas, estas semanas a sido un poco de todo, la verdad no me apetecía subir nada y no tenia ganas , y luego pille el Cov, y a pesar de tener muchas horas encerrada es lo que menos me apetecía, ya que entre el virus y la casa que se me caía encima, en fin vamos a comenzar hacer un movimiento del coche en 2d nuestro coche se va mover hacia todas las direcciones

nuestro coche se moverá en estas direcciones, el script es muy sencillo

lo primero que vamos hacer, es incorporar nuestro coche, a este lo pondremos un boxcollider 2D y un rigbody2d , con la gravedad 0

y a este mismo coche le pondremos el siguiente Script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;

public class movimiento02 : MonoBehaviour
{

    public float velocidad;
    public float rotacion;
    private Rigidbody2D rb;



    void Start()
    {
        rb = GetComponent<Rigidbody2D>();

    }

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

    {


        float h = -Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");

        Vector2 speed = transform.up * (v * velocidad);

        rb.AddForce(speed);

        float direction = Vector2.Dot(rb.velocity, rb.GetRelativeVector(Vector2.up));
        if (direction >= 0.0f)
        {
            rb.rotation += h * rotacion * (rb.velocity.magnitude / 5.0f);

        }
        else
        {
            rb.rotation -= h * rotacion * (rb.velocity.magnitude / 5.0f);

        }

        Vector2 forward = new Vector2(0.0f, 0.5f);
        float steeringRightAngle;
        if (rb.angularVelocity > 0)
        {
            steeringRightAngle = -90;
        }
        else
        {
            steeringRightAngle = 90;
        }

        Vector2 rightAngleFromForward = Quaternion.AngleAxis(steeringRightAngle, Vector3.forward) * forward;
        Debug.DrawLine((Vector3)rb.position, (Vector3)rb.GetRelativePoint(rightAngleFromForward), Color.blue);

        float driftForce = Vector2.Dot(rb.velocity, rb.GetRelativeVector(rightAngleFromForward.normalized));

        Vector2 relativeForce = (rightAngleFromForward.normalized * -1.0f) * (driftForce * 10.0f);


        Debug.DrawLine((Vector3)rb.position, (Vector3)rb.GetRelativePoint(relativeForce), Color.black);

        rb.AddForce(rb.GetRelativeVector(relativeForce));

    }
}

ya tendríamos nuestro juego, ahora en velocidad le pondré un 1, yo le tengo

3 y rotación 20 para que rote lo suficiente

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *