Hello!
I have a billiard ball, with this script:
void Update () {
transform.position += Vector3.one*Velocity;
Velocity *= 0.98f;
}
I need to hit the ball so that it rolls a distance of exactly 250 units.
How do I calculate what to set as the ball’s velocity, so that it would reach my target distance, whether it’s 250, or any other number?
Here’s my Flash prototype , but as you can see, I didn’t quite get to an accurate solution. I (shamefully) just simulated the ball at the target destination, and marched backwards (cheating).
My game is this , I’m working on the AI.
How about instead of all that weirdness, you use an ease method of some sort… like you would in flash w/ a tween.
Here are various tween functions defined:
using UnityEngine;
using System;
namespace com.spacepuppy.Tween
{
/// <summary>
/// Represents an eased interpolation w/ respect to time.
///
/// float t, float b, float c, float d
/// </summary>
/// <param name="current">how long into the ease are we</param>
/// <param name="initialValue">starting value if current were 0</param>
/// <param name="totalChange">total change in the value (not the end value, but the end - start)</param>
/// <param name="duration">the total amount of time (when current == duration, the returned value will == initial + totalChange)</param>
/// <returns></returns>
public delegate float Ease(float current, float initialValue, float totalChange, float duration);
public enum EaseStyle : int
{
This file has been truncated. show original
They all have the shape:
ease(float current, float initialValue, float totalChange, float dur)
With a coroutine you can do this:
void Start()
{
StartCoroutine(EaseMethods.QuadEaseIn, this.transform.position, this.transform.position + Vector3.one * 250f, 3.0f));
}
IEnumerator EaseTowards(Ease easeMethod, Vector3 start, Vector3 end, float dur)
{
float t = 0f;
Vector3 v = end - start;
Vector3 len = v.magnitude;
v.Normalize();
while(t < dur)
{
this.transform.position = start + v * easeMethod(t, 0f, 1f, dur) * len;
yield return null;
}
this.transform.position = end;
}
Note the linked source for the ease methods is actually part of a tween library of mine.
There are other tween libraries as well like iTween and HOTween that are similar.