Home > Net >  Unity Physics Sphere Movement (wheel movement)
Unity Physics Sphere Movement (wheel movement)

Time:08-18

I'm making a sphere move over a plane object. I'm trying to make the movement similar to the movement of a wheel, but I don't want to use the Wheel Collider component. I am using torque to move the sphere back and forth and I am using the rigidbody rotation (Because I read that it is not a good practice to perform these transformations directly on the geometry), but the rotation (steering) part is not working, the sphere continues to follow in same direction even rotating. Here's code below:

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

public class SphereMovement : MonoBehaviour
{
    float maxTorque = 30.0f;
    float maxSteerAngle = 30.0f;

    void Start()
    {
        
    }

    void FixedUpdate()
    {
        var deltaRotation = GetComponent<Rigidbody>().rotation * Quaternion.Euler(new Vector3(maxSteerAngle * Input.GetAxis("Horizontal") * Time.deltaTime, 0, 0));

        GetComponent<Rigidbody>().rotation = deltaRotation;

        GetComponent<Rigidbody>().AddTorque(new Vector3(maxTorque * Input.GetAxis("Vertical") * Time.deltaTime, 0, 0)); 
    }
}

Can someone help me?

CodePudding user response:

  1. Cache your GetComponent calls to improve performance (see below)

  2. You are applying torque into global x direction, you probably want to move "forward" (depending on the rotation of the wheel). transform.forward is your friend

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class SphereMovement : MonoBehaviour
    {
        float maxTorque = 30.0f;
        float maxSteerAngle = 30.0f;
        private Rigidbody rb;
    
        void Start()
        {
            rb = GetComponent<Rigidbody>();
        }
    
        void FixedUpdate()
        {
            var deltaRotation = rb .rotation * Quaternion.Euler(new Vector3(maxSteerAngle * Input.GetAxis("Horizontal") * Time.deltaTime, 0, 0));
    
            GetComponent<Rigidbody>().rotation = deltaRotation;
    
            GetComponent<Rigidbody>().AddTorque(transform.forward * (maxTorque * Input.GetAxis("Vertical") * Time.deltaTime); 
    
        }
    }
    

If your setup is otherwise rotated, you can try transform.right or transform.up

CodePudding user response:

The problem is here:

GetComponent<Rigidbody>().AddTorque(new Vector3(maxTorque * Input.GetAxis("Vertical") * Time.deltaTime, 0, 0));

Your torque is always being applied along the global X axis, so it doesn't matter which way the sphere object is rotated. Think of it like this -- no matter which way you rotate a soccer ball, if you spin it in a northwards direction, it will roll north. For your approach to work, you need to take your torque force and apply it along the vector you want to move, rather than always the global X axis.

  • Related