Monday, May 27, 2013

Lerps of Faith

I've been stuck in a test level for weeks - weeks! I finally got something together that I'm willing to live with, but I still don't like it much. The simple-sounding problem was that I needed, in various places, to move an object from point A to point B, in some cases speeding up as it leaves A, in other cases slowing down as it approaches B. Thank Christ I didn't need both at the same time or I'd still be working on it.

Several game development environments support this sort of thing natively with easing functions, but Unity is apparently not among them. Seems like an odd thing to leave out, but the Unity philosophy seems to be that if people want something badly enough, some user will eventually code it up and offer it to everyone else, possibly for a profit, and for this use case one need look no further than iTween, or if one's pockets are empty one could conceivably go to the community and base a solution on something like MathFx.

Granted, there's also the option of hooking my objects up to Unity's animation system, but that felt like using a bazooka on a mosquito, and I'm not sure the kind of easing I want is easy to get to. I had a hunch that I could probably get close enough to what I needed without anything so complex. Turns out I was sort of right, the Lerp function took care of me on the slowing down side, but the speeding up side took a little more head-scratching. Below is what I came up with, you'd attach it to a cube or whatever and then flip the bool to switch between modes.

This was one of those weird little bottleneck problems that is pretty unimportant in the grand scheme of things, but somehow had the power to bring my project to a grinding halt because it felt like it ought to be easy, and not being able to solve it had cascading negative effects on my confidence and motivation. This solution still looks a little weird, but no weirder than anything else in my project, so I'm calling it good.

using UnityEngine;
using System.Collections;

public class test_smoothlerp : MonoBehaviour {

GameObject cube;
Vector3 beginPoint;
Vector3 endPoint;
float startTime;
float tripDist;
float acc;
bool speedUp = true;

void Start () {
cube = GameObject.Find("Cube");
print ("cube = " + cube);

tripDist = 150.0f;

beginPoint = cube.transform.position;
print ("beginPoint = " + beginPoint);
endPoint = new Vector3(cube.transform.position.x + tripDist, cube.transform.position.y,
print ("endPoint = " + endPoint);

acc = 0.01f;

void Update () {
//speed up
if (acc < 1.0f)
acc += 0.01f;
Vector3 nextPos = new Vector3(cube.transform.position.x + (tripDist*acc), 0.0f, 0.0f);
print (nextPos);
if (nextPos.x < endPoint.x)
cube.transform.position = Vector3.Lerp(beginPoint, nextPos, Time.time);
print ("done");
//slow down
cube.transform.position = Vector3.Lerp(cube.transform.position, endPoint, Time.time);

No comments:

Post a Comment