- Home /
Question by
unity_qYF9IhUfSdNuiw · Sep 03, 2020 at 09:08 PM ·
c#torquecarssteering
A* Pathfinding and Driving Cars. How do I calculate the torque when the waypoint is perpendicular to the car
I use the following code to drive my car, the problem is if the next waypoint is perpendicular to the car it will not accelerate. What would be the best way do this I heard about PID Controller, but all examples I have found used a fixed Torque.
using Pathfinding;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
public Transform target;
public float maxSteeringAngle = 30f;
public float speed = 200f;
public float nextWaypointDistance = 3f;
public float stopDistance = 1f;
private Vector3 relativeWaypointPosition = new Vector3(0f, 0f, 0f);
[SerializeField]
private float inputSteer = 0.0f;
[SerializeField]
private float inputTorque = 0.0f;
Path path;
Vector3 movement;
int currentWaypoint = 0;
bool reachedEndOfPath = false;
Seeker seeker;
[SerializeField]
bool followTarget;
public float InputSteer { get => inputSteer; set => inputSteer = value; }
public float InputTorque { get => inputTorque; set => inputTorque = value; }
// Start is called before the first frame update
void Start()
{
GameObject targetObject = GameObject.FindGameObjectWithTag("PlayerTarget");
target = targetObject.transform;
if (target != null)
{
seeker = GetComponent<Seeker>();
followTarget = true;
InvokeRepeating("UpdatePath", 0f, 0.5f);
}
}
private void UpdatePath()
{
if (seeker.IsDone())
seeker.StartPath(transform.position, target.position, OnPathComplete);
}
private void OnPathComplete(Path p)
{
if (!p.error)
{
path = p;
currentWaypoint = 0;
}
}
private void Update()
{
InputSteer = 0.0f;
InputTorque = 0.0f;
if (!followTarget)
return;
float distanceToTarget = Vector3.Distance(transform.position, target.position);
if (distanceToTarget < stopDistance)
return;
if (path == null)
return;
if (currentWaypoint >= path.vectorPath.Count)
{
reachedEndOfPath = true;
return;
}
else
{
reachedEndOfPath = false;
}
movement = ((Vector3)path.vectorPath[currentWaypoint] - transform.position).normalized;
UpdateSteeringAndTorque();
float distance = Vector3.Distance(transform.position, path.vectorPath[currentWaypoint]);
if (distance < nextWaypointDistance)
{
currentWaypoint++;
}
}
public void SetFollowTargetOn()
{
followTarget = true;
InvokeRepeating("UpdatePath", 0f, 0.5f);
}
public void SetFollowTargetOff()
{
followTarget = false;
CancelInvoke();
}
void UpdateSteeringAndTorque()
{
if (path.vectorPath.Count > 0)
{
relativeWaypointPosition = transform.InverseTransformPoint(path.vectorPath[currentWaypoint]);
}
InputSteer = (relativeWaypointPosition.x / relativeWaypointPosition.magnitude);
InputTorque = (relativeWaypointPosition.z / relativeWaypointPosition.magnitude);
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613011155im_/https://answers.unity.com/themes/thub/images/avi.jpg)