Home > Back-end >  Ball won't move when coding it to do so
Ball won't move when coding it to do so

Time:09-15

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);
    }

}

CodePudding user response:

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.

CodePudding user response:

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;
public Rigidbody rb; //Get the rigid body component of the current object

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, forceNumber);
    rig.AddForce(movement*speed, ForceMode.Force);
}

Hope it helps you.

  • Related