I used AddForce in my movement script for the player movement but when I play the game at first my player is moving but then He stops. I noticed that when this happens the Rigidbody velocity at X is decreased to 0.
I’ll paste the whole script here because I’m not sure what makes this happen but the movement itself happens in lines 91-99(The left movement doesn’t work yet so ignore it):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
public bool IsFacingRight = true;
public bool IsMoving;
public bool IsOnGround;
public bool IsCurrentPlayer;
public bool DeafultKey = true;
public KeyCode KYBLeft;
public KeyCode KYBRight;
public KeyCode KYBJump;
public KeyCode KYBFireBall;
Rigidbody2D rigidbody2;
Animator Animator;
float MaxSpeed = 30;
float Speed;
float accelaration = 4f;
public float JumpForce = 10;
public int serialNumber;
string AnimIsRight = "IsFacingRight";
string AnimIsMoving = "IsMoving";
string AnimIsOnGround = "IsOnGround";
public GameObject LinkedFlame;
public Vector2 _moveInput;
private void Awake()
{
serialNumber = Random.Range(0, 999999999);
}
// Start is called before the first frame update
void Start()
{
Animator = GetComponent<Animator>();
if (DeafultKey)
{
KYBLeft = KeyCode.A;
KYBRight = KeyCode.D;
KYBJump = KeyCode.Space;
KYBFireBall = KeyCode.F;
}
rigidbody2 = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && IsOnGround && IsCurrentPlayer)
{
IsOnGround = false;
rigidbody2.AddForce(Vector2.up * JumpForce, ForceMode2D.Impulse);
}
_moveInput.x = Input.GetAxisRaw("Horizontal");
}
private void FixedUpdate()
{
if (IsCurrentPlayer)
{
Controls();
}
else
{
PlayerAnimation(IsMoving, IsFacingRight, IsOnGround);
}
if (!IsCurrentPlayer)
{
}
rigidbody2.constraints = RigidbodyConstraints2D.FreezePositionX;
rigidbody2.constraints = RigidbodyConstraints2D.FreezeRotation;
}
void Controls()
{
Speed = _moveInput.x * MaxSpeed;
if (Input.GetKey(KYBRight))
{
IsFacingRight = true;
IsMoving = true;
float SpeedDif = Speed - rigidbody2.velocity.x;
float movement = SpeedDif * accelaration;
rigidbody2.AddForce(movement * Vector2.right);
print(movement);
}
else if (Input.GetKey(KYBLeft))
{
IsFacingRight= false;
IsMoving = true;
//transform.Translate(Vector2.left * speed);
}
else
{
IsMoving = false;
}
PlayerAnimation(IsMoving, IsFacingRight, IsOnGround);
}
void PlayerAnimation(bool Move, bool FRight, bool OGround)
{
Animator.SetBool(AnimIsMoving, Move);
Animator.SetBool(AnimIsRight, FRight);
Animator.SetBool(AnimIsOnGround, OGround);
}
private void OnTriggerStay2D(Collider2D collision)
{
IsOnGround = true;
}
}