Here I am trying to change the value of DirectionX when I press a space it works but I have to press more than once to change.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player_Movement_script : MonoBehaviour
{
public float moveSpeed = 1f;
public float DirectionX=1;
Vector2 DirectionMovement;
void FixedUpdate()
{
if (Input.GetKey(KeyCode.Space))
{
if (DirectionX > 0)
{
DirectionX = -1;
}
else if (DirectionX <0)
{
DirectionX = 1;
}
}
DirectionMovement = new Vector2(DirectionX, 1f);
transform.Translate(DirectionMovement * moveSpeed * Time.deltaTime);
}
}
CodePudding user response:
Three points:
You rather want to use
GetKeyDown
which is true only once per key press.Otherwise your key press might get tracked twice so you immediately change the direction back again.
you should get single event user input in
Update
in order to not miss a frame.And then as soon as there is physics involved - which I guess since you use
FixedUpdate
rather do not useTransform
at all but rather go through theRigodbody2D
component
So something like
[SerializeField] private Rigidbody2D _rigidbody;
void Awake ()
{
if(!_rigidbody) _rigidbody = GetComponent<Rigidbody2D>();
}
void Update ()
{
if (Input.GetKeyDown(KeyCode.Space))
{
DirectionX *= -1;
}
}
void FixedUpdate()
{
// Only overwrite the X velocity!
var velocity = _rigidbody.velocity;
velocity.x = DirectionX * moveSpeed;
_rigidbody.velocity = velocity;
}