Hey so i’m new to this stuff and cant for the life of me figure out why this wont work. I previously watched a youtube video on basic stuff but then I changed the code so I was able to set my own velocity for the movement. In doing so it now only goes one way when I hold down one of the keys and its the d key.
please help
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private Transform groundCheckTransform = null;
public LayerMask playerMask;
private float horizontalInput;
private bool jumpKeyWasPressed;
private Rigidbody rIgidbody;
private bool isGrounded;
private float movementSpeed;
// Start is called before the first frame update
void Start()
{
rIgidbody = GetComponent<Rigidbody>();
horizontalInput = 0;
movementSpeed = 0;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("space"))
{
jumpKeyWasPressed = true;
}
horizontalInput = Input.GetAxis("Horizontal");
}
// use for phsyics shit that needs to be updated frame by frame
private void FixedUpdate ()
{
if (Input.GetKey("d"))
{
movementSpeed = 2;
rIgidbody.velocity = new Vector3(movementSpeed, rIgidbody.velocity.y, 0);
}
else
{
movementSpeed = 0;
}
if (Input.GetKey("a"))
{
movementSpeed = -2;
rIgidbody.velocity = new Vector3(movementSpeed, rIgidbody.velocity.y, 0);
}
else
{
movementSpeed = 0;
}
rIgidbody.velocity = new Vector3(movementSpeed, rIgidbody.velocity.y, 0);
if (Physics.OverlapSphere(groundCheckTransform.position, 0.3f, playerMask).Length == 0)
{
return;
}
if (isGrounded == false)
{
return;
}
if (jumpKeyWasPressed)
{
rIgidbody.AddForce(Vector3.up * 5, ForceMode.VelocityChange);
jumpKeyWasPressed = false;
}
}
void OnCollisionEnter(Collision collision)
{
isGrounded = true;
}
void OnCollisionExit(Collision collision)
{
isGrounded = false;
}
}