I don’t know why, Im trying to make a camera that will move forward instead of clipping through the wall. Heres the code
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
[SerializeField] private Camera _Camera;
[SerializeField] private GameObject _HeadBone;
[SerializeField] private Animator _AnimationController;
[SerializeField] private float _Speed;
[SerializeField] private float _WalkSpeed;
[SerializeField] private float _RunSpeed;
[SerializeField] private float _JumpHeight;
[SerializeField] private float _Gravity;
[SerializeField] private bool _IsGrounded;
public Vector2 _Sensitivity;
public float _RotY;
public float _RotX;
private Quaternion _OriginRot;
private Rigidbody _RigidBody;
private Vector3 _OriginLocalPos;
void Start () {
_RigidBody = GetComponent<Rigidbody> ();
_OriginRot = _HeadBone.transform.localRotation;
_OriginLocalPos = _Camera.transform.localPosition;
_RotY = 0;
_RigidBody.freezeRotation = true;
_RigidBody.useGravity = false;
Cursor.lockState = CursorLockMode.Locked;
}
void FixedUpdate () {
if (_IsGrounded) {
Vector3 _DesiredMotion = new Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical"));
_DesiredMotion = transform.TransformDirection (_DesiredMotion);
_DesiredMotion *= _Speed;
Vector3 Velocity = _RigidBody.velocity;
Vector3 DeltaVelocity = (_DesiredMotion - Velocity);
DeltaVelocity.x = Mathf.Clamp (DeltaVelocity.x, -_WalkSpeed, _WalkSpeed);
DeltaVelocity.z = Mathf.Clamp (DeltaVelocity.z, -_WalkSpeed, _WalkSpeed);
DeltaVelocity.y = 0;
_RigidBody.AddForce (DeltaVelocity, ForceMode.VelocityChange);
if (_IsGrounded && Input.GetButton ("Jump")) {
_RigidBody.velocity = new Vector3 (Velocity.x, Mathf.Sqrt (2 * _JumpHeight * _Gravity), Velocity.z);
}
}
_RotX += Input.GetAxis ("Mouse X") * _Sensitivity.x;
_RotY += Input.GetAxis ("Mouse Y") * _Sensitivity.y;
_RotY = Mathf.Clamp (_RotY, -50, 70);
Quaternion _QuaternionX = Quaternion.AngleAxis (_RotX, Vector3.up);
Quaternion _QuaternionY = Quaternion.AngleAxis (_RotY, Vector3.up);
_HeadBone.transform.localRotation = _OriginRot * _QuaternionY;
_RigidBody.transform.localRotation = _OriginRot * _QuaternionX;
// Gravity and grounding switch.
_RigidBody.AddForce(new Vector3 (0, -_Gravity * _RigidBody.mass, 0));
_IsGrounded = false;
}
void Update () {
/// HERES THE CAMERA BUMPER
RaycastHit _Intersect;
Vector3 _Heading = _Camera.transform.position - _HeadBone.transform.position;
float _Distance = _Heading.magnitude;
Vector3 _Direction = _Heading / _Distance;
if (Physics.Raycast (_HeadBone.transform.position, _Direction, out _Intersect, _Distance))
_Camera.transform.position = _Intersect.point;
else
_Camera.transform.localPosition = _OriginLocalPos;
Debug.DrawRay (_HeadBone.transform.position, _Direction, Color.magenta);
Debug.DrawLine (_Intersect.point, _Intersect.point + new Vector3 (0, 5, 0));
Debug.Log (_Intersect.point);
}
void OnCollisionStay () {
_IsGrounded = true;
}
}