LayaAir 自旋轉的小球跟隨鼠標移動

這個小球 還時在不一樣的旋轉中 oop

class Ball extends Laya.Sprite{

    private static cached:boolean = false;
    private body:Laya.Sprite;

    constructor(){
        super();
        this.init();
    }

    public init():void{
        if(!Ball.cached){
            Ball.cached = true;
            this.body = new Laya.Sprite();
            this.body.loadImage("war/ball.png");
            this.body.pivot(12,12);
        }
        this.addChild(this.body);
        Laya.timer.frameLoop(1,this,this.animate);    
    }

    private animate(e):void{
		this.body.rotation += 10;
	}
}

 首先計算出 小球和鼠標之間的角度. 而後根據角度 計算出下一個座標點的位置this

class Main{

    private ball:Ball;
    private speed:number = 5;

    constructor()
    {
			Laya.init(1100, 619, Laya.WebGL);
            Laya.loader.load("res/atlas/war.atlas",Laya.Handler.create(this,this.onLoaded),null,Laya.Loader.ATLAS);
    }

    private onLoaded():void{
            this.ball = new Ball();
            Laya.stage.addChild(this.ball);
		    this.ball.x = Laya.stage.width / 2;
		    this.ball.y = Laya.stage.height / 2;
            
            Laya.timer.frameLoop(1,this,this.onEnterFrame);
    }

    private onEnterFrame():void{
        //計算出角度
        let dx:number = Laya.stage.mouseX - this.ball.x;
        let dy:number = Laya.stage.mouseY - this.ball.y;
        let angle:number = Math.atan2(dy,dx);  //弧度制
        console.info(angle); 
        
        //能夠根據弧度旋轉 這個例子不須要 由於小球本身是不停轉動的
        //this.ball.rotation = angle;

        //根據弧度 計算出目標點座標
        this.ball.x += Math.cos(angle)*this.speed;
        this.ball.y += Math.sin(angle)*this.speed;
    }
}
new Main();
相關文章
相關標籤/搜索