3rd Person Character Vertical Movement
Hello!
I'm super new to unity and I'm making my first little project, but I've ran into some issues regarding my code. I am just trying to make a simple physics based movement for my character using a Rigidbody system. I've gotten most things to work, such as a Jump mechanic, Midair control and horizontal movement.
Here's where I've ran into some issues. I can't seem to figure out a way to make my character move vertically. When pressing the A or the D key, it will still move horizontally and I have no idea as to why that is and I can't seem to locate the problem.
I will post my code below , maybe someone can see a problem with it. I'd really appreciate some help!
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class playerMovement : MonoBehaviour { [SerializeField] public Transform groundCheckTransform = null; [SerializeField] private LayerMask playerMask;
private bool jumpKeyWasPressed;
private float horizontalInput;
private float verticalInput;
private Rigidbody rigidbodyComponent;
private int hiddenMechanic;
// Start is called before the first frame update
void Start()
{
rigidbodyComponent = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
jumpKeyWasPressed = true;
}
rigidbodyComponent = GetComponent<Rigidbody>();
{
if (Input.GetKey(KeyCode.A))
{
Debug.Log("A Button");
rigidbodyComponent.AddForce(Vector3.left);
}
if (Input.GetKey(KeyCode.D))
{
Debug.Log("D Button");
rigidbodyComponent.AddForce(Vector3.right);
}
if (Input.GetKey(KeyCode.W))
{
Debug.Log("W Button");
rigidbodyComponent.AddForce(Vector3.up);
}
if (Input.GetKey(KeyCode.S))
{
Debug.Log("S Button");
rigidbodyComponent.AddForce(Vector3.down);
}
}
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
}
private void FixedUpdate()
{
rigidbodyComponent.velocity = new Vector3(horizontalInput + verticalInput, rigidbodyComponent.velocity.y, 0);
if (Physics.OverlapSphere(groundCheckTransform.position, 0.1f, playerMask).Length == 0)
{
return;
}
// Hidden mechanic (some kind of super jump, not yet decided)
if (jumpKeyWasPressed)
{
float jumpPower = 5f;
if (hiddenMechanic > 0)
{
jumpPower *= 2;
hiddenMechanic--;
}
rigidbodyComponent.AddForce(Vector3.up * jumpPower, ForceMode.VelocityChange);
jumpKeyWasPressed = false;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == 7)
{
Destroy(other.gameObject);
hiddenMechanic++;
}
}
}
Your answer
Follow this Question
Related Questions
Swipe Power Limit in a ball 0 Answers
Making a pivot focused game 0 Answers
Movement and Jump with animator 0 Answers
Why isn't my player moving down? 0 Answers
animator and script issue 0 Answers