How to make a ball rolling while following a curve path made with ways point?
I've already know how to create ways point from this youtube: link video I want to make game like Rotator in Google Play Store (see this video). That ball can roll along curve path and while keep rotating. Meanwhile in the youtube video, I tried it to change the object to sphere. It seems that it cannot rotate to its forward direction. I tried to add this code below, but it doesn't follow the curve path I make. Anyone can help me?
RigidBody().AddForce(Vector3.forward * moveSpeed, ForceMode.Impulse); //move forward automatically
Anyone can help me out which part I should learn for this problem?
Answer by Vega4Life · Dec 17, 2018 at 09:57 PM
Hi. This is just something I threw together really quick, but it should give you an idea of how to do it.
using UnityEngine;
// Put on the ball object and add some waypoints
public class BallMover : MonoBehaviour
{
[SerializeField] GameObject[] points;
[SerializeField] Rigidbody body;
[SerializeField] float force = 5f;
int pointIndex = -1;
bool movementComplete;
Vector3 heading;
void Start()
{
GetNextPoint();
}
void FixedUpdate()
{
MoveBall();
}
void MoveBall()
{
if (movementComplete == false)
{
if (Vector3.Distance(points[pointIndex].transform.position, transform.position) <= 0.2f)
{
GetNextPoint();
}
else
{
body.velocity = heading * force;
}
}
}
void GetNextPoint()
{
pointIndex++;
if (pointIndex < points.Length)
{
heading = (points[pointIndex].transform.position - transform.position).normalized;
}
else
{
movementComplete = true;
// Stop all the things
body.velocity = body.angularVelocity = Vector3.zero;
}
}
}
I use rigidbody.velocity in this type of situation because I want to have total control over the speed of the ball. If we use addForce(), then the speed is additive and I would need a way to keep that under control.
Just add to your ball gameObject, then place some empty gameObject waypoints. Hope it helps!