Posts Tagged smoothdamp

Smoothed Vector3, Quaternions and floats in Unity



Download

I’ve put together a set of structs to handle changing the values of floats, Vector3s and Quaternions over time. It’s very simple to use and is far easier to read than having lots of time recognising code or referenced veclocities in the middle of your game logic. You replace a Vector3 (say) with a SmoothVector3 in your code, set its target value, smoothing method and duration, then read its value over time in an Update() call. I use this when I don’t have a gameObject to hand to apply iTween or when I may want to keep changing the position and don’t want to mess with iTween and need the control at every Update call.

You can choose a smoothing mode from slerp, lerp, SmoothDamp and SmoothStep.

To use this in your code, download the .cs file and put it in your Assets/Plugins folder.

Here is an example from JavaScript on how to use the SmoothVector3 to smoothly move an object when a key is pressed.


#pragma strict

var pos : SmoothVector3;

function Start () {
	//Construct a SmoothVector3 by assigning a normal Vector3
	//this initializes the position
	pos = transform.position;

	//The following are optional and override the standard settings

	//Duration in seconds of the transform
	pos.Duration = 1;
	//Smoothing mode from damp, smooth, lerp and slerp
	pos.Mode = SmoothingMode.damp;
}

function Update () {
	if(Input.anyKeyDown)
	{
		//Setting the Value of the SmoothVector3 starts the interpolation
		//This will move the item 1 unit in X,Y from the current position
		//(which may be an interpolated value)
		pos.Value = pos.Value + Vector3(1,1,0);

		//In this example this is equivalent to
		//pos.Value = transform.position + Vector3(1,1,0);

		//An alternative is to use the .Target property
		//which is the current targeted position - in our example
		//this maintains the object on exact boundaries and means
		//that it will accelerate if you click lots of times
		//pos.Value = pos.Target + Vector3(1,1,0);

		//Or of course you could just set the value
		//pos.Value = Vector3(100,100,0);

	}

	//A SmoothVector3 can be used in place of a Vector3 in assignments
	transform.position = pos;

}

With Vector3 and Quaternions you can directly affect the individual elements to set the targeted value.

       mySmoothVec3.x = mySmoothVec3.x + 100;

, , , , , , ,

1 Comment