MichiBros
MichiBros

Reputation: 142

Player teleports instead of moving smoothly

When I first coded the movement of the player, it was all fine except one thing: when it collided with walls it vibrated/jittered. So I replaced the transform.Translate() I was using to Rigidbody2D.Moveposition(); It worked like a charm. But now whenever I move it vibrates/kind of teleport, and it doesn't move smoothly.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Player : MonoBehaviour
{


    private Rigidbody2D rigidbody2d;


    float MovementX = 0;
    float MovementY = 0;

    public float Speed = 5f;


    void Start()
    {
        rigidbody2d = GetComponent<Rigidbody2D>();


    }


    void Update()
    {




        if (MovementX < 0)
            transform.localScale = new Vector2(-1, 1);
        if (MovementX > 0)
            transform.localScale = new Vector2(1, 1);


        //transform.Translate(Movement);
        //rigidbody2d.MovePosition(Movement);
        //rigidbody2d.AddForce(Movement * Speed);



    }

    private void FixedUpdate()
    {
        MovementX = Input.GetAxis("Horizontal") * Speed * Time.deltaTime;
        MovementY = Input.GetAxis("Vertical") * Speed * Time.deltaTime;

        //MovementX = movementJoystick.Horizontal * Speed * Time.deltaTime;
        //MovementY = movementJoystick.Vertical * Speed * Time.deltaTime;

        Vector2 Movement = new Vector2(transform.position.x + MovementX, transform.position.y + MovementY);
        rigidbody2d.MovePosition(Movement);
    }


}

As I said before, the player should move smoothly but it doesn't. If you want, I can try to link a video of tha gameplay.

Thanks in advance.

Upvotes: 0

Views: 384

Answers (1)

Branden
Branden

Reputation: 347

The Rigidbody2D has a property called velocity, if you set the velocity of your rigidbody in the update of your class, this should solve your problem. The code might look something like this:

rigidbody2d.velocity = new Vector2(MovementX, MovementY);;

Upvotes: 1

Related Questions