- Home /
Question by
kekkinalldey · Oct 15, 2016 at 12:46 PM ·
c#charactercontrollerfirst-person-controller
How to make object move where the camera points?
I've been trying to setup a first person movement script, and the problem I've found is it will only move on the X axis, and Z axis, as a global position. I'm wondering how would I go about making it so, that when I point it in a direction it will swap it's axis to that direction, if that makes sense. Basically, how would I go about making a first person movement script work.
using UnityEngine;
using System.Collections;
public class FPSMovement : MonoBehaviour
{
public Camera FPSCam;
public float speed = 4.0f;
public float runSpeed = 4.5f;
public float Stamina = 100.0f;
public float gravity = 20.0f;
private Vector3 moveDirection = Vector3.zero;
private CharacterController controller;
// Use this for initialization
void Start()
{
controller = GetComponent<CharacterController>();
}
void run()
{
if (Stamina > 0.0f)
{
moveDirection *= runSpeed;
Stamina -= Time.deltaTime * 2.0f;
Debug.Log(runSpeed);
}
}
// Update is called once per frame
void Update()
{
if (controller.isGrounded)
{
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.InverseTransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetKey(KeyCode.LeftShift))
run();
else if (Stamina != 100)
Stamina += Time.deltaTime * 2.0f;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
Comment
Answer by b1gry4n · Oct 15, 2016 at 01:00 PM
moveDirection = new Vector3(Input.GetAxis("Horizontal") * speed * FPSCam.transform.right, 0, Input.GetAxis("Vertical") * speed * FPSCam.transform.forward);
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Character Controller 1 Answer
Finding an object is within an another 3 Answers
False = true, what am I doing wrong? 2 Answers