效果:鼠标在舞台上拖动,黄色三角形沿着红色贝塞尔曲线移动
贝塞尔曲线.png
语言:AS3
完整代码:在main.as中实例并调用即可
//main.as中的调用代码
var bz:BezierPath1=new BezierPath1();
bz.x=50;
bz.y=50;
Laya.stage.addChild(bz);
bz.init();
//代码块
package {
import laya.maths.Point;
import laya.display.Sprite;
import laya.maths.Bezier;
import laya.events.Event;
public class BezierPath1 extends Sprite{
//初始化
public function init(): void {
this.addChild(logo)
//画三角形
logo.pos(10, 10)
logo.graphics.drawPoly(-10, -20, [0, 50, 25, 0, 50, 50], "#ffff00");
//起始点、拉力点、终点
var points:Array = [logo.x, logo.y,400, 100, 100, 500]
//使用贝塞尔曲线工具类生成60个点
var array:Array = Bezier.I.getBezierPoints(points, 60)
console.log("array:", array)
for(var i:int = 0;i<array.length;i=i+2){
pointArray.push(new Point(array[i],array[i+1]));
}
//画轨道
for(i= 0;i<pointArray.length;i=i+2){
var logo1: Sprite = new Sprite();
this.addChild(logo1)
logo1.graphics.drawCircle(pointArray[i].x, pointArray[i].y, 2, 'red')
}
//添加舞台点击事件
Laya.stage.on(Event.MOUSE_DOWN,this,onTouchDown);
}
private var logo: Sprite = new Sprite();
private var pointArray:Array=[];
private var mouseDownY:int=0;
private var touchBeginIndex:int=0;
private var curIndex:int=0;
public function onTouchDown(e:Event):void{
mouseDownY = Laya.stage.mouseY;
touchBeginIndex = curIndex;
//注册鼠标移动、抬起事件
Laya.stage.on(Event.MOUSE_MOVE,this,onTouchMove);
Laya.stage.on(Event.MOUSE_UP,this,onMouseUp);
Laya.stage.on(Event.MOUSE_OUT,this,onMouseUp);
}
public function onTouchMove(e:Event):void{
var curY:Number = Laya.stage.mouseY;
var delta:Number = curY-mouseDownY;
//计算移动速率
curIndex = touchBeginIndex+Math.floor(delta/6); //拖动和移动速度
if(curIndex<0){
curIndex+=pointArray.length-1;//到尾部
}
if(curIndex>pointArray.length-1){//到头部
curIndex-=pointArray.length-1
}
//修改三角形位置
logo.pos(pointArray[curIndex].x, pointArray[curIndex].y)
}
public function onMouseUp(e:Event):void{
//解绑事件
Laya.stage.off(Event.MOUSE_MOVE,this,onTouchMove);
Laya.stage.off(Event.MOUSE_UP,this,onMouseUp);
Laya.stage.off(Event.MOUSE_OUT,this,onMouseUp);
}
}
}
参考链接:https://blog.csdn.net/nicepainkiller/article/details/91390452
网友评论