I am making a 2.5D type of game in a 3D environment where the player can move in all 3 axis (z for forward and backward, y for jumping and x for the depth of the level). I have a script where if the A or D keys are pressed (based on a Boolean), the player will turn 90 degrees (if it is set to false, which is the default) or turn -90 degrees (if it is set to true). My problem is that the “forward” movement for the player is always in the world’s Z axis rather than the player’s Z axis. How can I make it so the player moves in either the local Z axis or the world’s X axis?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public CharacterController controller;
public float speed = 6f;
public float gravity = 9.81f;
public float jumpSpeed = 5f;
public float rotationSpeed = 90f;
private float directionY;
public Transform player;
public bool turned = false;
// Update is called once per frame
void Update()
{
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(0f, 0f, vertical).normalized;
direction.y = directionY;
//character movement
controller.Move(direction * speed * Time.deltaTime);
//turnign
if (turned == false && Input.GetKey(KeyCode.D))
{
transform.Rotate (0, 90, 0);
turned = true;
}
else
{
if(turned == true && Input.GetKey(KeyCode.A))
{
transform.Rotate (0, -90, 0);
turned = false;
}
}
//jumping
if (Input.GetButtonDown("Jump") && controller.isGrounded)
{
directionY = jumpSpeed;
}
directionY -= gravity * Time.deltaTime;
}
}