- Home /
The question is answered, right answer was accepted
Problem between my player jump and player movement
i made a simple jump and movement, but i have a problem. If i comment the 75 line (in FixedUpdate) of my code "rb2d.MovePosition(rb2d.position + mov speed Time.deltaTime);" my jump work fine, but if i not coment this line, the jump not work and the player gravity is like too less, but not change in the inspector, i'm confussed, i'm a bit noob and i dont what happends. Thanks!
public class PlayerMovement : MonoBehaviour
{
[Header("Movement")]
[SerializeField] float speed = 4f;
[SerializeField] bool canMove;
CircleCollider2D feetColl;
private Vector2 mov = new Vector2(1, 1);
Animator anim;
Rigidbody2D rb2d;
[Header("Jump")]
[Range(1,10)]
[SerializeField] float jumpVelocity = 1f;
public bool jumpRequest;
public float fallMultiplier = 2.5f;
public float lowJumpMultiplier = 2f;
void Awake()
{
rb2d = GetComponent<Rigidbody2D>();
}
void Start()
{
anim = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
feetColl = GetComponent<CircleCollider2D>();
canMove = true;
}
void Update()
{
if (canMove)
{
// Falling();
JumpRequest();
}
}
/*
private void Falling()
{
if (!feetColl.IsTouchingLayers(LayerMask.GetMask("ground")))
{
anim.SetBool("falling", false);
}
else
{
anim.SetBool("falling", true);
}
}
*/
private void Run()
{
mov = new Vector2(Input.GetAxisRaw("Horizontal"), 0f);
if (mov != Vector2.zero)
{
anim.SetFloat("movX", mov.x);
anim.SetBool("running", true);
}
else
{
anim.SetBool("running", false);
}
}
void FixedUpdate()
{
//Movement
rb2d.MovePosition(rb2d.position + mov * speed * Time.deltaTime);
Run();
Jump();
}
private void JumpRequest()
{
if (Input.GetButtonDown("space"))
{
jumpRequest = true;
}
}
private void Jump()
{
if (jumpRequest && !feetColl.IsTouchingLayers(LayerMask.GetMask("ground")))
{
return;
}
if (jumpRequest)
{
rb2d.AddForce(Vector2.up * jumpVelocity, ForceMode2D.Impulse);
anim.SetTrigger("jump");
Debug.Log("jump");
jumpRequest = false;
}
if (rb2d.velocity.y < 0)
{
rb2d.gravityScale = fallMultiplier;
}
else if (rb2d.velocity.y > 0 && !Input.GetButton("space"))
{
rb2d.gravityScale = lowJumpMultiplier;
}
else
{
rb2d.gravityScale = 1f;
}
}
}
Answer by Dawdlebird · Jul 30, 2019 at 11:08 AM
Your moveposition directly sets your rigidbody's position. This basicly negates any forces you apply, and your jump depends on force. If you want to use forces, you should also do your moving left and right by applying forces in either direction, or do something like setting velocity (but then keeping the velocity.y intact to keep your jump/fall happening)
Perhaps you could also store velocity.y before you apply MovePosition, and then reapply velocity.y after. Either way, I suspect that MovePosition is your culprit here. Does it also interfere with falling speed?
Additionaly: you're using Time.deltaTime in a fixedUpdate, but there is a Time.fixedDeltaTime for that.