Ball won't move when coding it to do so

Viewed 61

When I run the following code in order to make a ball move, it does not seem to work, even though I do not get any errors.

Would anybody be able to give me a helping hand?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class playercontroller : MonoBehaviour
{
    public float speed = 0;

    private Rigidbody rb;

    private float movementX;
    private float movementY;

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


    private void OnMove(InputValue movementValue)
    {
        Vector2 movementVector = movementValue.Get<Vector2>();

        movementX = movementVector.x;
        movementY = movementVector.y;
    }

    private void FixedUpdate()
    {
        Vector3 movement = new Vector3(movementX, 0.0f, movementY);

        rb.AddForce(movement * speed);
    }

}
2 Answers

First check if movementX and Y have some value, idk what type of steering you are using but it's crucial if the are 0 then there is something wrong with onMove.

Add a force in a direction to the rigid body, and the rigid body will start to move. This method is suitable for simulating the rigid body motion under the action of external force.

public float speed = 20f;
private Rigidbody rb; //Get the rigid body component of the current object

private float movementX;
private float movementY;

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

 private void OnMove(InputValue movementValue)
{
    Vector2 movementVector = movementValue.Get<Vector2>();

    movementX = movementVector.x;
    movementY = movementVector.y;
}

void FixedUpdate()
{
    Vector3 movement = new Vector3(movementX, 0, movementY);
    rb.AddForce(movement*speed, ForceMode.Force);
}

Using the up, down, left, and right arrow keys, the control cube is pushed from all sides.

private Rigidbody rig;

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

void Update () {
    float hor = Input.GetAxis("Horizontal");
    float ver = Input.GetAxis("Vertical");
    float up = Mathf.Sqrt(hor * hor + ver * ver);
    if (up > 0.1) {
        rig.AddForce(new Vector3(hor, 0, ver) * 10); // add thrust
    }
}

Hope it helps you.

Related