Skip to content

Instantly share code, notes, and snippets.

@pmarinr
Last active November 17, 2020 16:42
Show Gist options
  • Save pmarinr/e73af5484ddb8cf1fe585f039f331357 to your computer and use it in GitHub Desktop.
Save pmarinr/e73af5484ddb8cf1fe585f039f331357 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class IAcoche : MonoBehaviour
{
// Start is called before the first frame update
float _movimientoX;
float _movimientoY;
Rigidbody2D _rb;
public float potencia = 5;
public float fuerzaGiro = 2;
public GameObject[] waypoints;
int _siguientewaypoint = 0;
int _totalWaypoints;
void Start()
{
_rb = GetComponent<Rigidbody2D>();
_totalWaypoints = waypoints.Length;
}
// Update is called once per frame
void Update()
{
_movimientoY = CalculaAcelerador();
_movimientoX = CalculaGiro();
_rb.AddForce(transform.up * _movimientoY * potencia);
_rb.AddTorque(-_movimientoX * fuerzaGiro);
}
float CalculaGiro()
{
float giro = 0;
Vector3 lookat = waypoints[_siguientewaypoint].transform.position - transform.position;
Vector3 perpendicular = Vector3.Cross(transform.forward, lookat);
float direccion = Vector3.Dot(perpendicular, transform.up);
Debug.DrawRay(transform.position, transform.up * direccion, Color.yellow);
if (direccion > 0.1f)
{
giro = 1f;
}
else if (direccion < -0.1)
{
giro = -1f;
}
return giro;
}
float CalculaAcelerador()
{
float acelerador = 1;
return acelerador;
}
private void OnTriggerEnter2D(Collider2D collision)
{
// Primero vemos si el objeto tiene el tag waypoint
if (collision.CompareTag("waypoint"))
{
// Ahora comprobamos que el objeto es el siguiente de la lista (Empezamos en cero)
if (collision.name == waypoints[_siguientewaypoint].name)
{
Debug.Log("Waypoint");
_siguientewaypoint++;
// Si hemos terminado todos los wp de la lista
if (_siguientewaypoint == _totalWaypoints)
{
_siguientewaypoint = 0;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment