Question by
unity_724497C4D6491215E60A · Apr 19, 2021 at 09:44 AM ·
c#unity 5
Stopping horizontal movement, but not vertical.
I'm working on an inventory system right now. I want the player not to be able to move when he's in his inventory, but the game to still continue. Below, inventory is just a image
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
//Variables
public float speed = 6.0F;
public float sprintSpeed = 10.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
public GameObject inventory;
void Update()
{
CharacterController controller = GetComponent<CharacterController>();
// is the controller on the ground?
if (controller.isGrounded && inventory.activeSelf == false)
{
//Feed moveDirection with input.
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
//Multiply it by speed.
if (Input.GetKey(KeyCode.LeftShift))
{
moveDirection *= sprintSpeed;
}
else
{
moveDirection *= speed;
}
//Jumping
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
//Applying gravity to the controller
moveDirection.y -= gravity * Time.deltaTime;
//Making the character move
if(inventory.activeSelf == false)
controller.Move(moveDirection * Time.deltaTime);
}
}
I stopped the use of the movement inputs when the inventory, but his momentum doesn't stop. A way I figured out was adding
if(inventory.activeSelf == false)
controller.Move(moveDirection * Time.deltaTime);
But that stops the movement completely but the player gets frozen midair which is not what I want. Is there a way to distinguish horizontal and vertical movement in that one line of code?
Comment