Hello, I am new here so I apologies for any mistakes. I have been making a monster truck game but keep having collision issues, the truck simply clips through objects and I haven’t been able to find any solutions I tried using rigidbody methods but then the truck no longer moves or moves uncontrollably fast I am completely lost…
here’s the code:
using UnityEngine;
public class VehicleControl: MonoBehaviour
{
public float moveSpeed = 10f; // Max speed
public float turnSpeed = 5f; // Turning speed
public float acceleration = 5f; // Acceleration speed
public float deceleration = 5f; // deceleration speed
public float brakeForce = 20f; // Brake power
private float currentSpeed = 0f; // current speed
private Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
HandleMovement();
HandleSteering();
}
private void HandleMovement()
{
float moveInput = Input.GetAxis("Vertical");
// Acceleration
if (moveInput > 0)
{
currentSpeed += moveInput * acceleration * Time.fixedDeltaTime;
}
// Deceleration (let off the gas)
else if (moveInput == 0 && currentSpeed > 0)
{
currentSpeed -= deceleration * Time.fixedDeltaTime;
}
// Braking (moving backwards or pressing down on the brake)
else if (moveInput < 0)
{
currentSpeed -= brakeForce * -moveInput * Time.fixedDeltaTime;
}
// Clamp the current speed to avoid exceeding max speed or going negative
currentSpeed = Mathf.Clamp(currentSpeed, 0f, moveSpeed);
// Apply the movement based on the current speed
Vector3 move = transform.forward * currentSpeed * Time.fixedDeltaTime;
rb.MovePosition(rb.position + move);
}
private void HandleSteering()
{
float turnInput = Input.GetAxis("Horizontal");
// Only allow turning if the car is moving forward or backward
if (currentSpeed > 0)
{
Quaternion turn = Quaternion.Euler(0f, turnInput * turnSpeed, 0f);
rb.MoveRotation(rb.rotation * turn);
}
}
}