2014-01-17 79 views
0

我正在尝试创建一个屏幕保护程序,并在其内容中有一个让我们称之为'主要鱼'的游泳场所。我设法做了主要鱼游泳的编码部分。现在我已经添加了更小的鱼,这是我能够做到的主要鱼类,但是我怎样才能让小鱼停留在主要鱼类的后面,因为它们不会与主鱼类或其他鱼类相撞。这是我迄今所做AS3:避免碰撞

这是鱼类(即下一个)

package 
{ 
    import flash.display.MovieClip; 
    import flash.events.Event; 
    import flash.geom.Point; 

    public class Fish extends MovieClip 
    { 
     var speed:Number = 3; 
     var target:Point; 

     public function Fish() 
     { 
      // constructor code 
      addEventListener(Event.ENTER_FRAME, update); 
     } 

     function update(e:Event) 
     { 
      //Point fish at main fish 
      var dx = MovieClip(parent).mainfish01.x - x; 
      var dy = MovieClip(parent).mainfish01.y - y; 
      var angle = Math.atan2(dy,dx)/Math.PI * 180; 
      rotation = angle; 

      //Move in the direction the fish is facing 
      x = x+Math.cos(rotation/180*Math.PI)*speed; 
      y = y+Math.sin(rotation/180*Math.PI)*speed; 

      //Calculate the distance to target 
      var hyp = Math.sqrt((dx*dx)+(dy*dy)); 
     } 
    } 
} 

回答

0

设置最高距离,然后更新位置

function update(e:Event) 
    { 
     //Point fish at main fish 
     var dx = MovieClip(parent).mainfish01.x - x; 
     var dy = MovieClip(parent).mainfish01.y - y; 
     var angle = Math.atan2(dy,dx)/Math.PI * 180; 
     rotation = angle; 


     //Calculate the distance to target 
     var hyp = Math.sqrt((dx*dx)+(dy*dy)); 

     // calculate based on size 
     var minDist = 10; 
     if(hyp > minDist){ 
      //Move in the direction the fish is facing 
      x = x+Math.cos(rotation/180*Math.PI)*speed; 
      y = y+Math.sin(rotation/180*Math.PI)*speed; 
     } 
    } 
+0

前检查的距离你不应该计算真正的距离,而是使用距离的平方,因为这样你可以避免计算一个平方根,这是一个很昂贵的函数,但是对于几条鱼,你不会注意到有什么不同。 – Daniel

+0

谢谢丹尼尔,它像一个魅力。最近我发现了一些看起来非常棒的转向行为。我只需要坐下来研究它,但是谢谢你。 – Saf