【发布时间】:2014-04-07 02:34:31
【问题描述】:
我想在我正在制作的游戏中进行宇宙飞船射击,但我似乎无法正确加载射击的位置。 我有一个名为 shot[] 的数组,当玩家按住鼠标按钮时,我想每 N 个刻度将 Shot() 对象推入其中。 所以基本上我希望 Shot() 的 x 属性等于我的 ship.x 属性和 y=ship.y。 然后我希望它有一个 Shot.dx 属性,该属性会根据光标是在画布中间上方还是波纹管(+3/-3)或中心的左侧或右侧(dy=+3/-3 )。
// Shooting
var shots = [] //Bullet array
//Object, which should be the position of the bullet.
function Shot() {
this.x=350
this.y=250;
this.dx=Shoot.x
this.dy=Shoot.y
}
//This keeps track of the cursor position in relation to the center of canvas.
function Shoot() {
started = false;
this.mousedown = function (ev) {
started = true;
};
this.mousemove = function (ev) {
if (started) {
if (ev.clientX>=350) this.x=3;
else this.x=-3;
if (ev.clientY>=250) this.y=3;
else this.y=-3;
}
};
this.mouseup = function (ev) {
started = false;
};
}
//The problem is, that when I set this.x in Shot() to be =ship.x the values
//dont get updated and it stays undefined after I push it into the array.
//Now I have it set to the center of canvas, but that it useless because it needs
//to move with the ship, but even now I am getting weird numbers and not the numbers
//that I actually put in. dx and dy dont get updated at all.
// Ship Model
var ship = {
x: 350,
y: 250,
lives: 3,
invulnerable: 0,
}
//Main function- pushes the objects into the array
function mainLoop() {
tick++
count()
interval()
chase()
console.log(started)
if (started && tick%20==0)
shots.push(new Shot());
keyboard()
display()
check()
requestAnimationFrame(mainLoop);
}
// Initialization
window.onload = function() {
// Setting variables
button = document.getElementById("button")
text = document.getElementById("text")
canvas = document.getElementById("canvas")
ctx = canvas.getContext("2d")
weapon = new Shoot();
canvas.onmousedown = weapon.mousedown;
canvas.onmousemove = weapon.mousemove;
canvas.onmouseup = weapon.mouseup;
requestAnimationFrame(mainLoop);
}
//I know this is a lot of code, but its all relevant. I am new to Javascript
//so I expect this to be some sort of a trivial error.
这是一个 JSfiddle,但我不知道它是如何工作的,所以我无法让它绘制画布,抱歉:http://jsfiddle.net/JH3M6/
【问题讨论】:
标签: javascript canvas