Hello, newbie here. As stated in the title, I want the character to move in the direction of the camera, but still allowing the character to face their direction of movement. For example, if i press “d” the character turns and moves right, but if the camera is turning right and i press “w” for forward, the character moves right in the game world. Basically like Dark Souls, GTA, or Assassin’s Creed
Movement code
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public static float playerSpeed = 3.5F;
public static float rollSpeed = 20.0F;
public static float sprint = 7f;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= playerSpeed;
if (Input.GetButtonUp("Roll"))
moveDirection.x = rollSpeed;
if (Input.GetButtonDown("Sprint")){
playerSpeed += sprint;
if (Input.GetButtonUp("Sprint"))
playerSpeed -= sprint;
}
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
Camera code(just mouse orbit in the wiki)
using UnityEngine;
using System.Collections;
[AddComponentMenu("Camera-Control/Mouse Orbit with zoom")]
public class MouseOrbit: MonoBehaviour {
public Transform target;
public float distance = 5.0f;
public float xSpeed = 120.0f;
public float ySpeed = 120.0f;
public float yMinLimit = -20f;
public float yMaxLimit = 80f;
public float distanceMin = .5f;
public float distanceMax = 15f;
float x = 0.0f;
float y = 0.0f;
// Use this for initialization
void Start () {
Vector3 angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
// Make the rigid body not change rotation
if (rigidbody)
rigidbody.freezeRotation = true;
}
void LateUpdate () {
if (target) {
x += Input.GetAxis("Mouse X") * xSpeed * distance * 0.02f;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
y = ClampAngle(y, yMinLimit, yMaxLimit);
Quaternion rotation = Quaternion.Euler(y, x, 0);
distance = Mathf.Clamp(distance - Input.GetAxis("Mouse ScrollWheel")*5, distanceMin, distanceMax);
RaycastHit hit;
if (Physics.Linecast (target.position, transform.position, out hit)) {
distance -= hit.distance;
}
Vector3 negDistance = new Vector3(0.0f, 0.0f, -distance);
Vector3 position = rotation * negDistance + target.position;
transform.rotation = rotation;
transform.position = position;
}
}
public static float ClampAngle(float angle, float min, float max)
{
if (angle < -360F)
angle += 360F;
if (angle > 360F)
angle -= 360F;
return Mathf.Clamp(angle, min, max);
}
}