K
K
KraGen.Developer2022-03-15 20:17:10
Unity
KraGen.Developer, 2022-03-15 20:17:10

How to make a static movement to the side?

Hello everyone, in general, the game is like a flappy bird. It is necessary that the player constantly moves to the side (for the player it is straight), I do it like this

void FixedUpdate(){
        rb.AddForce(target.right * 0.06f, ForceMode.Impulse);  
    }

but that's when i jump
public void Move(){
        if(Energy > 0){
            rb.AddForce(target.up * jumpForce,ForceMode.Impulse);
            if(!Nimb)Energy--;
        }

then this speed increases to the side and if you jump several times in a row, the player gains more speed, which is not necessary at all. How can this be fixed? help me please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
K0TlK, 2022-03-15
@KraGenDeveloper

Use normal movement, not via AddForce.
Use Rigidbody's velocity to set a specific speed, not some force.
Here is an example:

using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class Bird : MonoBehaviour
{
    [SerializeField] private float _speed;
    [SerializeField] private float _jumpSpeed;

    private Rigidbody2D _rb;

    private void Start()
    {
        _rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        Move();
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }
    }

    private void Jump()
    {
        var velocity = _rb.velocity;
        velocity.y = _jumpSpeed;
        _rb.velocity = velocity;
    }

    private void Move()
    {
        var velocity = _rb.velocity;
        velocity.x = _speed;
        _rb.velocity = velocity;
    }

}

In the Move method, we set the speed along the X axis, thereby the character moves to the right. In the Jump method, we set the speed along the Y axis and the character jumps. This is just an example of how you can move through velocity, implement everything according to your needs. Using movement through velocity, it will be much easier to balance the game by simply changing the speed to the desired one, rather than guessing how much force you need to apply to an object in order for it to jump higher.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question