slowly rotate an object towards another object
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) b开发者_开发百科elow 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.
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
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});
hey i know this post is a bit old but i'v been looking for a solution myself for this and finally found a way to solve this problem! yey me :D
this loop will make myAngle turn towards the mouse
//loop
function loop(e:Event) {
var targetAngle:Number=Math.atan2(myStage.mouseY-y,myStage.mouseX-x);
if(Math.abs(myAngle-targetAngle)>Math.PI){
if(targetAngle>0){
targetAngle-=Math.PI*2;
}else{
targetAngle+=Math.PI*2;
}
}
if(myAngle>Math.PI){
myAngle -=Math.PI*2;
}
if(myAngle<-Math.PI){
myAngle +=Math.PI*2;
}
//this is to check if the angle is wide enough, otherwise myAngle will jiggle back and forth
if (Math.abs(myAngle-targetAngle)>0.1) {
if (myAngle-targetAngle<0) {
myAngle+=0.1;
} else {
myAngle-=0.1;
}
}
精彩评论