Физическое движение персонажа, в сторону, в которую он смотрит в Unity 3D
Итак, я сделал нормальное(вроде) физическое движение объекта(персонажа), но как сделать так, чтобы он шёл в сторону, в которую смотрит(Я поворачиваю игрока вместе с камерой)? Реализация движения: PlayerMovement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private Rigidbody _rigidbody;
[SerializeField] private SurfaceSlider _surfaceSlider;
[SerializeField] private float _speed;
public void Move(Vector3 direction)
{
Vector3 directionAlongSurface = _surfaceSlider.Project(direction.normalized);
print(transform.forward);
Vector3 offset = directionAlongSurface * (_speed * Time.deltaTime);
_rigidbody.MovePosition(_rigidbody.position + offset);
}
}
KeyboardInput:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KeyboardInput : MonoBehaviour
{
[SerializeField] private PlayerMovement _movement;
[SerializeField] private FollowCamera _camera;
private void Update()
{
float vertical = Input.GetAxis("Vertical");
float horizontal = Input.GetAxis("Horizontal");
float vertical_cam = Input.GetAxis("Mouse Y");
float horizontal_cam = Input.GetAxis("Mouse X");
_movement.Move(new Vector3(horizontal, 0, vertical));
_camera.Rotate(new Vector3(-vertical_cam, horizontal_cam, 0));
}
}
SurfaceSlider:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SurfaceSlider : MonoBehaviour
{
private Vector3 _normal;
public Vector3 Project(Vector3 forward)
{
return forward - Vector3.Dot(forward, _normal) * _normal;
}
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag != "Finish")
{
_normal = collision.contacts[0].normal;
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.black;
Gizmos.DrawLine(transform.position, transform.position + _normal * 3);
Gizmos.color = Color.red;
Gizmos.DrawLine(transform.position, transform.position + Project(transform.forward));
}
}