With the help of some friends I made a movement script for a 3d game I’m making. The script is supposed to allow the player to move a vehicle forward & backwards and then turn the vehicle. The script itself doesn’t return any errors, but in game the vehicle immediately starts rotating to the right, speeding up if it’s left alone and if it makes a full 180 degree turn, then the controls invert. So I was wondering if anyone could help figure out what is wrong with the script. It’s coded in CSharp.
using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine;
public class MoveScript : MonoBehaviour {
public float mySpeed;
public float speed = 5.0f;
private Boolean canMove;
private Boolean turnLeft = false;
private Boolean turnRight = false;
private float rotationVal;
private float temp = 0f;
private Transform myTransform;
Rigidbody obj;
float camRayLength = 100f;
int wallMask;
void Awake()
{
wallMask = LayerMask.GetMask("Walls");
obj = GetComponent<Rigidbody>();
}
void Update()
{
if (canMove)
{
if (Input.GetKeyDown("left"))
{
turnLeft = true;
//TurnLeft();
}
if (Input.GetKeyDown("right"))
{
turnRight = true;
//TurnRight();
}
}
Vector3 moveDir = Vector3.zero;
//moveDir.y = Input.GetAxis("Horizontal");
//transform.Rotate(moveDir);
transform.position += mySpeed * Time.deltaTime * (moveDir * 2f);
Vector3 speedUp = Vector3.zero;
moveDir.x = Input.GetAxis("Vertical");
transform.position += mySpeed * Time.deltaTime * -moveDir;
//Turning();
}
void LateUpdate()
{
if (turnLeft)
{
if (temp > 90)
{
turnLeft = false;
temp = 0f;
}
else
{
rotationVal = Mathf.Lerp(0f, 90f, Time.deltaTime);
myTransform.Rotate(0, rotationVal, 0);
temp += rotationVal;
}
}
else if (turnRight)
{
if (temp < -90)
{
turnRight = false;
temp = 0f;
}
else
{
rotationVal = Mathf.Lerp(0f, -90f, Time.deltaTime);
myTransform.Rotate(0, rotationVal, 0);
temp += rotationVal;
}
}
}
void Turning()
{
Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit wallHit;
if(Physics.Raycast(camRay, out wallHit, camRayLength, wallMask))
{
Vector3 playerToMouse = wallHit.point - transform.position;
playerToMouse.x = 0f;
playerToMouse.z = 0f;
Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
obj.MoveRotation(newRotation);
}
}
}