- Home /
Question by
Sam3million · Mar 30, 2018 at 09:13 PM ·
c#cameramovementrelative
Move player relative to camera
I am very new to c#. I want to make it so my character moves based on where the camera is looking. So if I turn the camera 180 then W still makes it go forward. I looked on the forums and found similar questions but I didn't see any answers that fit my case. I am using rb.addForce to move my character and I didn't see any answers that used that. Keep in mind I am very new to unity and c#. You might have to tell me exactly what to do. Any answers would be helpful.
Here is my playercontroller script:
using UnityEngine;
using System.Collections;
public class playercontroller : MonoBehaviour
{
public float speed;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
}
}
and here is my camerachange script:
using UnityEngine;
using System.Collections;
public class CameraChange : MonoBehaviour
{
public float turnSpeed = 0.0f;
public Transform player;
public float height = 5f;
public float distance = -10f;
public bool movable = false;
private Vector3 offsetX;
void Start()
{;
offsetX = new Vector3(0, 2, 5);
}
void Update()
{
{
if (Input.GetKey(KeyCode.Mouse1))
{
movable = true;
if (movable == true)
{
turnSpeed = 4.0f;
}
}
else
{
movable = false;
turnSpeed = 0.0f;
}
}
offsetX = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offsetX;
transform.position = player.position + offsetX;
transform.LookAt(player.position);
}
}
Comment