Skip to content

Instantly share code, notes, and snippets.

@melsov
Created December 6, 2018 13:18
Show Gist options
  • Save melsov/d27ab6347b40fa314cb5064c2b954d05 to your computer and use it in GitHub Desktop.
Save melsov/d27ab6347b40fa314cb5064c2b954d05 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RaceCarMove : MonoBehaviour {
Rigidbody rb;
public float fAccel = 15f;
public float lrAccel = 3f;
public float turnSpeed = .5f;
public float breakStrength = .1f;
//keys
public KeyCode kForward = KeyCode.W;
public KeyCode kLeft = KeyCode.A;
public KeyCode kRight = KeyCode.D;
public KeyCode kBreak = KeyCode.C;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
RaycastHit rayHit;
bool GroundNormal(out Vector3 normal)
{
Ray r = new Ray(transform.position, transform.up * -1f);
if(Physics.Raycast(r.origin, r.direction, out rayHit, 5f))
{
normal = rayHit.normal;
return true;
}
normal = Vector3.zero;
return false;
}
//credit: https://math.stackexchange.com/questions/633181/formula-to-project-a-vector-onto-a-plane
Vector3 ProjectedForwardDirFromGroundNormal()
{
var fw = transform.forward;
Vector3 normal;
if(GroundNormal(out normal))
{
// projection of forward vec onto the plane normal
var nProjection = Vector3.Dot(fw, normal) * normal;
// subtract the projection from the foward vec
return fw - nProjection;
}
return fw;
}
//private void OnDrawGizmos()
//{
// Gizmos.color = Color.red;
// var from = transform.position + Vector3.up * 1.5f;
// Vector3 normal;
// GroundNormal(out normal);
// Gizmos.DrawLine(from, from + normal * 3f);
// Gizmos.color = Color.green;
// Gizmos.DrawLine(from, from + ProjectedForwardDirFromGroundNormal() * 3f);
//}
void FixedUpdate ()
{
if (Input.GetKey(kForward))
{
var fw = ProjectedForwardDirFromGroundNormal();
var push = fw * fAccel;
rb.AddForce(push);
}
if (Input.GetKey(KeyCode.D))
{
var push = transform.right;
push.y = 0f;
push = push.normalized;
push *= lrAccel;
rb.AddForce(push, ForceMode.Impulse);
}
if(Input.GetKey(KeyCode.A))
{
var push = transform.right;
push.y = 0f;
push = push.normalized;
push *= -1f * lrAccel;
rb.AddForce(push, ForceMode.Impulse);
}
//breaks
if (Input.GetKey(KeyCode.C))
{
var push = rb.velocity * breakStrength * -1f;
push.y = 0f;
rb.AddForce(push, ForceMode.Impulse);
}
if (Mathf.Abs(rb.velocity.x) + Mathf.Abs(rb.velocity.z) > 1f)
{
// car / player should 'slerp' towards its own velocity
Quaternion curRo = transform.rotation;
Quaternion targetRo = Quaternion.LookRotation(rb.velocity, Vector3.up);
rb.MoveRotation(Quaternion.Slerp(curRo, targetRo, turnSpeed * Time.deltaTime));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment