Hi all,
I’m designing a car game for a research experiment. When I run the code the car starts moving without pressing any button on the keyboard. It is controllable with keys but it goes backward. I also changed the orientation of the car and the wheels positions but it doesn’t solve.
Does anyone has any idea in this case?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleCarController : MonoBehaviour
{
public void GetInput()
{
m_horizontalInput = Input.GetAxis("Horizontal") * motorForce;
m_verticalInput = Input.GetAxis("Vertical") * motorForce;
//Debug.Log("Vertical Input: " + m_verticalInput);
}
public void Steer()
{
m_steeringAngle = maxSteerAngle * m_horizontalInput;
frontDriverW.steerAngle = m_steeringAngle;
frontPassengerW.steerAngle = m_steeringAngle;
}
private void Accelerate()
{
frontDriverW.motorTorque = m_verticalInput *motorForce;
frontPassengerW.motorTorque = m_verticalInput *motorForce;
rearDriverW.motorTorque = m_verticalInput *motorForce;
rearPassengerW.motorTorque = m_verticalInput *motorForce;
}
private void UpdateWheelPoses()
{
UpdateWheelPoses(frontDriverW, frontDriverT);
UpdateWheelPoses(frontPassengerW, frontPassengerT);
UpdateWheelPoses(rearDriverW, rearDriverT);
UpdateWheelPoses(rearPassengerW, rearPassengerT);
}
private void UpdateWheelPoses(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()
{
if (Input.GetKeyDown(KeyCode.Space) && !hasStarted)
{
hasStarted = true;
}
if (hasStarted)
{
GetInput();
Steer();
Accelerate();
}
UpdateWheelPoses();
}
//could be modified by horizontal input
private float m_horizontalInput;
private float m_verticalInput;
private float m_steeringAngle;
private float currentAcceleration;
private float currentBreakForce;
public WheelCollider frontDriverW, frontPassengerW;
public WheelCollider rearDriverW, rearPassengerW;
public Transform frontDriverT, frontPassengerT;
public Transform rearDriverT, rearPassengerT;
public float maxSteerAngle = 30;
public float motorForce = 50;
public float acceleration = 100f;
public float breakingForce = 20;
private bool hasStarted = false;
}