K
K
KGUZ6942020-04-24 13:35:25
C++ / C#
KGUZ694, 2020-04-24 13:35:25

Why is the Rigidbody bouncing?

Hello! I'm trying to make a simple runner. I made two separate scripts for the character and the section of the road along which he moves. The character script moves it left, right and allows it to jump, while the road script moves it back to create the illusion of running. In both scripts, movement is called with a rigidbody. The problem is that when the game starts, the character (now, on the prototype, his role is played by a cube) sinks a little into the road and starts bouncing. Because of this, every time I press the spacebar, the character jumps to a different height. Help me please!!!

If necessary, I can upload a file with assets. All that remains is to drag the road and the camera into the character hierarchy window. They are already configured and will immediately fall into the desired position.

Character control code:
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private Rigidbody playerRb;

    public float turnSpeed = 10,
                 distanceBetweenLines = 1.5f,
                 x = 0,
                 gravityMod = 4,
                 jumpForce = 12;
    public bool isOnGround = true;

    void Start()
    {
        playerRb = GetComponent<Rigidbody>();
        Physics.gravity *= gravityMod;
    }

    void Update()
    {
        // Повороты в стороны
        if (Input.GetKeyDown(KeyCode.A) && x > -distanceBetweenLines)
        {
            x -= distanceBetweenLines;
        }
        else if (Input.GetKeyDown(KeyCode.D) && x < distanceBetweenLines)
        {
            x += distanceBetweenLines;
        }

        // Прыжки
        if (Input.GetKey(KeyCode.Space) && isOnGround)
        {
            playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
            isOnGround = false;
        }
    }

    private void FixedUpdate()
    {
        playerRb.MovePosition(new Vector3(Mathf.Lerp(transform.position.x, x, turnSpeed * Time.deltaTime), transform.position.y, transform.position.z));
    }

    void OnCollisionEnter(Collision collision)
    {
        // Проверяем на дороге ли мы
        if (collision.gameObject.CompareTag("Road"))
        {
            isOnGround = true;
        }
    }
}



Road traffic code:
using UnityEngine;

public class MoveBack : MonoBehaviour
{
    private Rigidbody rb;
    static float speed = 20;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        rb.velocity = (Vector3.back * speed);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timur Pokrovsky, 2020-04-24
@Makaroshka007

Why not move the character instead of the road?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question