Hi My Game is an Arcade Racing game. thats why i want to use addforce for forward and backward movement. My Problem is that the Car/Rigidbody is getting stuck if the Car has 0 velocity. it start turning upside down and may get unstuck after a couple of forward/backward keystrokes. Making the player spawn in mid air and dropping down fixes the issue if playerinput is there before hitting the ground. I am Using addforce only for forward and backwards. Turning is determind by the steeringangle with wheel colliders (2 wheels in front). rear wheels for force.
I am pretty new to C# and Unity in general. And i couldnt find anything that would make the player not get stuck there. maybe you guys can help me`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleCarController : MonoBehaviour
{
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
public void GetInput()
{
m_horizontalInput = Input.GetAxis("Horizontal");
m_verticalInput = Input.GetAxis("Vertical");
}
public void Accelerate()
{
if (Input.GetKey(KeyCode.W) || ButtonF.Forward == 1)
{
Vector3 forceToAdd = transform.forward;
forceToAdd.y = 0;
rb.AddForce(forceToAdd * speed * 10);
}
else if (Input.GetKey(KeyCode.S) || ButtonB.Back == 1)
{
Vector3 forceToAdd = -transform.forward;
forceToAdd.y = 0;
rb.AddForce(forceToAdd * speed * 10);
}
Vector3 locVel = transform.InverseTransformDirection(rb.velocity);
locVel = new Vector3(0, locVel.y, locVel.z);
rb.velocity = new Vector3(transform.TransformDirection(locVel).x, rb.velocity.y, transform.TransformDirection(locVel).z);
// Abruf des Gameobjektes
var gmj = GameObject.Find("CountdownText");
//Nullcheck um Nullrefex zu vermeiden
if (gmj != null)
{
//Abruf des Script objetes aus dem Gameobject
var comp = gmj.GetComponent<CountdownTimer>();
if (comp != null)
{
//Script Aktivitätscheck
if (!comp?.countdownActive ?? false)
{
rb.velocity = new Vector3(0, 0, transform.TransformDirection(locVel).z);
}
}
}
}
private void UpdateWheelPoses()
{
UpdateWheelPose(rearDriverW, rearDriverT);
UpdateWheelPose(rearPassengerW, rearPassengerT);
}
private void UpdateWheelPose(WheelCollider _collider, Transform _transform)
{
Vector3 _pos = _transform.position;
Quaternion _quat = _transform.rotation;
_collider.GetWorldPose(out _pos, out _quat);
_transform.position = _pos;
_transform.rotation = _quat;
}
private void FixedUpdate()
{
Accelerate();
UpdateWheelPoses();
GetInput();
}
private float m_horizontalInput;
private float m_verticalInput;
private float m_steeringAngle;
public float speed;
public WheelCollider rearDriverW, rearPassengerW;
public Transform rearDriverT, rearPassengerT;
public float motorForce = 50;
public float gravityMultiplier;
}`