我正在阅读this关于如何使用CreateJS制作宇宙飞船跟随光标的文章+, 我想知道如何让实体向鼠标位置移动,但也可以面向它旋转。
以下是没有轮换的示例的fiddle 和代码
var canvas = document.getElementById("Canvas");
var ship;
var stage;
var assets;
var loader;
var serverString = "http://source.tutsplus.com/gamedev/authors/JamesTyner/SmoothMoves/";
var stageHeight = 600;
var stageWidth = 600;
var shipHeight = 64;
var shipWidth = 64;
var easingAmount = 0.15;
var text;
stage = new createjs.Stage(canvas);
assets = [];
manifest = [{
src: serverString + "ship.png",
id: "character"
}];
loader = new createjs.LoadQueue(false);
loader.onComplete = handleComplete;
loader.onFileLoad = handleFileLoad;
loader.loadManifest(manifest);
function handleFileLoad(event) {
var id = event.item.id;
var result = loader.getResult(id);
ship = new createjs.Bitmap(result);
ship.x = (stageWidth / 2) - shipWidth;
ship.y = stageHeight - shipHeight;
ship.regX = shipWidth/2;
ship.regY = shipHeight/2;
}
function handleComplete() {
stage.addChild(ship);
text = new createjs.Text("Click To Activate", "20px Arial", "#000000");
text.x = 200;
text.y = stageHeight / 2;
stage.addChild(text);
stage.update();
}
stage.onMouseDown = function () {
stage.removeChild(text);
createjs.Ticker.addEventListener("tick", tick);
};
function tick(event) {
var xDistance = stage.getStage().mouseX - ship.x;
var yDistance = stage.getStage().mouseY - ship.y;
var distance = Math.sqrt(xDistance * xDistance + yDistance * yDistance);
if (distance > 1) {
ship.x += xDistance * easingAmount;
ship.y += yDistance * easingAmount;
}
stage.update();
}
谢谢大家
答案 0 :(得分:1)
首先以度数计算船只和鼠标指针之间的角度:
var mousePointerPosition = {
x: stage.getStage().mouseX,
y: stage.getStage().mouseY
};
var spaceShipPosition = {
x: ship.x,
y: ship.y
};
var angle = Math.atan2(
spaceShipPosition.y - mousePointerPosition.y,
spaceShipPosition.x - mousePointerPosition.x
) * 180 / Math.PI;
然后旋转宇宙飞船:
ship.rotation = ( angle > 180 ? -angle : angle ) + 90;
如果angle
超过180,我们将角度反转以使船转向另一个方向。此外,我将+ 90
添加到角度,因为与鼠标位置相比,船只旋转了90度。
Js Fiddle:http://jsfiddle.net/nkZjR/200/