views:

222

answers:

2

I have an object that points in the direction of another object (i.e. it rotates to the direction that the second objects x and y coordinates are at) below is the code I use.

var distx = target.x - x;
var disty = target.y - y;

var angle:Number = Math.atan2(disty, distx);


var vx:Number = Math.cos(angle) * cspeed;
var vy:Number = Math.sin(angle) * cspeed;
rotation = angle * 180/Math.PI;

x += vx;
y += vy;

as you can see. Not only does it rotate towards the target object, but it also moves towards it too. When I play the movie, the object instantly points to the targeted object and moves towards it.

I would like for it to slowly turn towards the object instead of instantly turning towards it. anyone know how to do this.

A: 

What about using a Tween to do it? You can use the built-in flash library fl.transitions.Tween or one of the many alternatives like Tweener or TweenLite.

For fl.transitions.Tween

import fl.transitions.Tween;
import fl.transitions.easing.*;
var myTween:Tween = new Tween(this, "rotation", Regular.easeOut, this.rotation, angle * 180/Math.PI, 3, true);

Using Tweener:

import com.caurina.transitions.Tweener
Tweener.addTween(this, {rotation:angle * 180 / Math.PI, time:3, transition:"easeOutQuad"});

Using TweenLite:

import com.greensock.*;
import com.greensock.easing.*;
TweenLite.to(this, 3, {rotation:angle * 180 / Math.PI, ease:Quad.easeOut});
sberry2A
Not too farmiluar with the significance of programmatic tweening.
numerical25
+1  A: 

I'd say try this function

function averageNums($a:Number, $b:Number, $f:Number=0.5):Number {
   var avg:Number = (Math.atan2( Math.sin($a)*($f) + Math.sin($b)*(1-$f) , Math.cos($a)*($f) + Math.cos($b)*(1-$f) ));
   return avg;
}

and rotation = averageNums(rotation/180*Math.PI,angle, 0.9)* 180/Math.PI;

the f number will let you have faster/slower rotation

there ARE issues with this way of doing it, like averaging 0 and 180

alternatively, you can use the loop class here: http://blog.daspoda.com/index.php?subaction=showfull&id=1238477904&archive=&start_from=&ucat=3&

Daniel
that actually worked perfect. Thanks alot
numerical25
glad it works, just be aware of the issue pointed out, this would occur when the object is exactly 0 or 180 degrees off.If you follow the trig there, what ends up happening is that the difference between the two y positions (that are exactly the same at that point) will be 0, and you can't devide by zero. So you might want to put an if statement to prevent the error event from happening
Daniel