Trying to get camera to follow mouse, and player movement to be relative to camera angle?
I want to make the camera follow the mouse, and for the player to move relative to the angle of the camera. For example, if the player presses 'w', it will addforce in whatever direction the camera is facing (but not vertically, I don't want the player to fly). How do I make this happen?
Current camera script (doesn't work properly, the camera can get twisted around): using UnityEngine;
public class FollowPlayer : MonoBehaviour {
public Transform player;
public Vector3 offset;
// Update is called once per frame
void Update () {
transform.position = player.position + offset;
//if (Input.GetMouseButton(1))
//{
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
Vector3 lookhere = new Vector3(-mouseY, mouseX, 0);
transform.Rotate(lookhere);
// }
}
}
Current Movement Script: using UnityEngine;
public class PlayerMovement : MonoBehaviour {
// this is a reference to the component RigidBody, called 'rb'
public Rigidbody rb;
public float ForwardForce = 2000f;
public float BackForce = 250f;
public float SideForce = 750f;
public PlayerMovement movement;
// We changed 'Update' to 'FixedUpdate' because we're messing with physics
void FixedUpdate()
{
if (Input.GetKey("w"))
{
// only executed if condition is met
// we added a forward force
rb.AddForce(0, 0, ForwardForce * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKey("s"))
{
// only executed if condition is met
// we added a forward force
rb.AddForce(0, 0, -ForwardForce * Time.deltaTime, ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
// only executed if condition is met
// we added a left force
rb.AddForce(-SideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("d"))
{
// only executed if condition is met
// we added a right force
rb.AddForce(SideForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y <= -1f)
{
FindObjectOfType<GameplayManager>().EndGame();
}
}
}
Your answer
Follow this Question
Related Questions
Unity 3D: Third person movement and mouse camera control 0 Answers
Mouvement issue with mouse input. 0 Answers
New Input System first person camera stutter. 0 Answers
Why is my MouseLook script not letting me look up? 0 Answers
having CharacterController movement in fixedupdate causes jerky movement on camera 3 Answers