2012-03-28 52 views
2

我正在尝试写一个蛇游戏。这非常简单,有一系列蛇形分段,它们都是精灵,它们都有xy的值。在每个游戏循环中,我想根据用户输入更新蛇段。蛇段在蛇游戏中跟随头部

注意:蛇的头部被定义为this.segments[0]。段数组的第一个元素是头部。

对我来说,根据用户输入更新蛇头似乎是合乎逻辑的,然后在头更新之后将每个蛇段跟随它。这是我的代码到目前为止:

public function update() 
{ 
    // Update snake head 
    this.segments[0].x += 10; 

    for (var i:Number = 1; i < this.segments.length; i++) 
    { 
     // Set the segments position to be the same as the one before it 
     this.segments[i].x = this.segments[i - 1].x; 
     this.segments[i].y = this.segments[i - 1].y; 
    } 
} 

希望你能看到你在这里做什么。我试图设置段x和y的值与它之前的值相同,因此它会“跟随”。

问题是,当我运行这段代码时,每个蛇段都堆积在同一个坐标的顶部,看起来像是一个运行的段。他们不遵循,他们在彼此的顶部。

对我来说,逻辑看起来很稳固,所以给了什么?

回答

1

嗯......

反向你的循环(做最后一段将第一)。

并做最后一个。


基本上,segment i抓住已经更新的i-1的位置。

1

你很近。您需要在计算中包含每个段的长度。尝试这样的事情

for (var i:Number = 1; i < this.segments.length; i++) 
{ 
    // Set the segments position to be the same as the one before it 
    //include the width or height of n-1 depending on how you're moving segments[0] 
    this.segments[i].x = this.segments[i - 1].x + this.segmants[i-1].width; 
    this.segments[i].y = this.segments[i - 1].y + this.segments[i-1].height; 
} 
1

您的第一项是正确的头this.segments [0]

然后你决定要更新以下段(从1开始),并把它设置为头部的位置。所以this.segments [1]将与相同this.segments [0]。由于它是一个循环,所以每个片段都将被设置为头部的位置,这就是为什么每个片段都堆在蛇的顶部。所以你应该从尾巴到头部来避免这种情况。

1

我不是数学知识,但我发现这对一些运动很有趣!

import flash.display.Sprite; 
import flash.events.Event; 
import flash.events.MouseEvent; 

var segments:Array = []; 

for (var i = 0; i < 10; i++){ 

    var circle:Sprite = new Sprite(); 
    circle.graphics.beginFill(0x00ADEF, 1); 
    circle.graphics.drawCircle(0,0, 10); 
    circle.graphics.endFill(); 

    segments.push(circle); 
    addChild(circle); 
} 

stage.addEventListener(Event.ENTER_FRAME, update); 
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove); 

function onMove(e:MouseEvent):void 
{ 
    this.segments[0].x = mouseX; 
    this.segments[0].y = mouseY; 
} 

function update(e:Event):void 
{ 

    for (var i:Number = 1; i < this.segments.length; i++) 
    { 
     // Set the segments position to be the same as the one before it 
     this.segments[i].x += (this.segments[i - 1].x - this.segments[i].x)/2; 
     this.segments[i].y += ((this.segments[i - 1].y - this.segments[i].y)/2 ) + this.segments[i - 1].height/2; 
    } 

} 
+0

旁注:任何人都知道如何添加一些角度,这取决于你的矢量加速度x,y? – Adrian 2012-03-28 23:45:27