您好我一直在关注炮弹物理以及如何在游戏中实施它们。
我想将重力应用于炮弹以及相对于鼠标的x和y速度 光标位置。所以炮弹向你的鼠标位置移动。
远离鼠标光标(从大炮开始),速度越高。
角度应与画布上光标的位置匹配。
我现在已经花了好几天的时间,所以现在我问。
谁知道使用javascript和canvas的好的炮弹物理?
units = 10,
pixelsPerMeter = stage.width / units,
startlaunch = Math.PI/4,
launchAngle = startlaunch;
bang = {
lastTime: 0,
gravity: 9.81,
applyGravity: function (elapsed) {
bullet1.velocityY = (this.gravity * elapsed) -
(launchVelocity * Math.sin(launchAngle));
},
updateBulletPosition: function (updateDelta) {
bullet1.left += bullet1.velocityX * (updateDelta) * pixelsPerMeter;
bullet1.top += bullet1.velocityY * (updateDelta) * pixelsPerMeter;
},
execute: function (bullet1, time) {
var updateDelta,
elapsedFlightTime;
if(bulletInFlight){
elapsedFrameTime = (time - this.lastTime)/1000;
elapsedFlightTime = (time - launchTime)/1000;
this.applyGravity(elapsedFlightTime);
this.updateBulletPosition(elapsedFrameTime);
}
this.lastTime = time;
}
}
cannon.rotation = cannon.on("tick", function(event) {
var angle = Math.atan2(stage.mouseY - cannon.y, stage.mouseX - cannon.x );
angle = angle * (180/Math.PI);
// The following if statement is optional and converts our angle from being
// -180 to +180 degrees to 0-360 degrees. It is completely optional
if(angle < 0){
angle = 360 - (-angle);}
// Atan2 results have 0 degrees point down the positive X axis, while our image is pointed up.
// Therefore we simply add 90 degrees to the rotation to orient our image
// If 0 degrees is to the right on your image, you do not need to add 90
cannon.rotation = 90 + angle;
});
var fire = false, gravity = 6, vy = 3, vx = 3;
oneback.on("click", function(e) {
bullet1.x = cannon.x;
bullet1.y = cannon.y;
scene1.addChild(bullet1);
fire = true;
//e.preventDefault();
bullet1.rotation = cannon.rotation;
if(fire == false){
bullet1.vx = Math.cos(bullet1.x-stage.mouseX) * this.vx;// used to be... this.bullet_speed'.
bullet1.vy = Math.sin(bullet1.y-stage.mouseY) * this.vy;
}
});
oneback.on("click", function(e){
e.preventDefault();
if(fire == true) {
loc = (stage.mouseX, stage.mouseY);
lastMouse.left = loc.x;
lastMouse.top = loc.y;
deltaX = Math.abs(lastMouse.left - bullet1.left);
deltaY = Math.abs(lastMouse.top - bullet1.top);
launchAngle = Math.atan(parseFloat(deltaY) / parseFloat (deltaX));
launchVelocity = 4 * deltaY / Math.sin (launchAngle) / pixelsPerMeter;
}
});
bullet1.on("tick", function(event){
if(fire == true){
bullet1.y += vy - gravity;
bullet1.x += vx - gravity;
// bullet1.y -= stage.mouseY;
//bullet1.x -= stage.mouseX;
//bullet1.x = direction - gravity;
//bullet1.y = direction - gravity;
}
});