Make Character Move Towards Facing Direction

Hi. I’ve googled forever but no solution works. I’ve tried using transform.forward, transform.eulerAngles, transform.TransformDirection, and some make it move towards its facing direction but then strafing etc breaks.

My control scheme means I can strafe left/right, walk backwards, walk forwards. All movement should be relative to the camera but I’m not sure how to do that.

Please take a look at my script and help me out.

using UnityEngine;
using System.Collections;

public class Platformer3DController : MonoBehaviour
{
    public float runSpeed = 6f;
    public float strafeSpeed = 6f;
    public float jumpSpeed = 10f;
    public float gravity = 21f;
    
    private Vector3 moveVector = Vector3.zero;
    private float velocity = 0f;
    
    public CharacterController CharacterController;
    public GameObject MainCamera;
    
    void Awake()
    {
        CharacterController = gameObject.GetComponent("CharacterController") as CharacterController;
    }
    
    void Start()
    {
        MainCamera = GameObject.FindGameObjectWithTag("MainCamera");
        Platformer3DGameController.GameScript.cameraTarget.transform.parent = transform;
        Platformer3DGameController.GameScript.cameraTarget.transform.position = transform.position;
    }
    
    void Update()
    {
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        AlignToCamera();
        ProcessMovement(h, v);
    }
    
    void ProcessMovement(float horizontal, float vertical)
    {
        float deadZone = 0.1f;
        moveVector = Vector3.zero;
        
        if(horizontal > deadZone || horizontal < -deadZone)
        {
            moveVector += new Vector3(horizontal, 0f, 0f);
        
        }
        if(vertical > deadZone || vertical < -deadZone)
        {
            moveVector += new Vector3(0f, 0f, vertical);
        }
        if(moveVector.magnitude > 1)
        {
            moveVector = Vector3.Normalize(moveVector);
        }
        moveVector.x *= strafeSpeed;
        moveVector.z *= runSpeed;
        moveVector.y = velocity;
        
        ProcessGravity();
        
        if(CharacterController.isGrounded && Input.GetButton("Jump"))
        {
            velocity = jumpSpeed;
        }
        
        CharacterController.Move(moveVector * Time.deltaTime);
        
    }
    
    void ProcessGravity()
    {
        if(!CharacterController.isGrounded)
        {
            moveVector.y -= gravity * Time.deltaTime;
            velocity = moveVector.y;
        }
    }
    
    void AlignToCamera()
    {
        transform.rotation = Quaternion.Euler(transform.eulerAngles.x, MainCamera.transform.eulerAngles.y, transform.eulerAngles.z);
    }
}

1 Answer

1

So I sort of had it right to begin with - transform.TransformDirection(moveVector) is what I wanted but I had it at the wrong place in the code so it wasn’t working.