Skip to content

Instantly share code, notes, and snippets.

@t0dd
Created December 22, 2017 16:34
Show Gist options
  • Save t0dd/2c4b88f24ac73b7f1d076e9a7d4b076e to your computer and use it in GitHub Desktop.
Save t0dd/2c4b88f24ac73b7f1d076e9a7d4b076e to your computer and use it in GitHub Desktop.
Kinematics used to develop a snake sprite
package {
import Segment;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import playerfiles.Player;
import playerfiles.Particle;
import flash.geom.Point;
public class Snake extends Sprite {
private var segments:Array;
private var numSegments:uint = 10;
public var target:Player;
public var speed:Number = 2;
public var velocity:Point = new Point();
public var snakex:Number = 0;
public var snakey:Number = 0;
public function Snake(t:Player)
{
target = t;
init();
}
private function init():void
{
segments = new Array();
for(var i:uint = 0; i < numSegments; i++)
{
var segment:Segment = new Segment(26, 6);
addChild(segment);
segments.push(segment);
}
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(event:Event):void
{
if(target.status!="Dead")drag(segments[0], target.x, target.y);
for(var i:uint = 1; i < numSegments; i++)
{
var segmentA:Segment = segments[i];
var segmentB:Segment = segments[i - 1];
otherdrag(segmentA, segmentB.x, segmentB.y);
}
}
private function drag(segment:Segment, xpos:Number, ypos:Number):void
{
var dx:Number = xpos - segment.x;
var dy:Number = ypos - segment.y;
var angle:Number = Math.atan2(dy, dx);
velocity.x = Math.cos(angle);
velocity.y = Math.sin(angle);
segment.rotation = angle * 180 / Math.PI;
var w:Number = segment.getPin().x - segment.x;
var h:Number = segment.getPin().y - segment.y;
segment.x += velocity.x*speed;
segment.y += velocity.y*speed;
snakex = segment.x;
snakey = segment.y;
}
private function otherdrag(segment:Segment, xpos:Number, ypos:Number):void
{
var dx:Number = xpos - segment.x;
var dy:Number = ypos - segment.y;
var angle:Number = Math.atan2(dy, dx);
velocity.x = Math.cos(angle);
velocity.y = Math.sin(angle);
segment.rotation = angle * 180 / Math.PI;
var w:Number = segment.getPin().x - segment.x;
var h:Number = segment.getPin().y - segment.y;
segment.x = xpos - w;
segment.y = ypos - h;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment