Javascript 游戏功能
我正试图让我的对象在Javascript 游戏功能,javascript,html5-canvas,Javascript,Html5 Canvas,我正试图让我的对象在中以一种完全运动的方式移动,这是我对javascript的理解(尽管还不多)。我必须做大量的研究,但我一事无成 我试着让我的游戏角色,在玩家的级别,移动。但是,它不会随着我的箭头键移动。控制台正在从我的函数接收日志,但角色没有移动 JS转储: const canvas = document.getElementById('Game-Screen'); const ctx = canvas.getContext('2d'); canvas.width = 1200; canva
中以一种完全运动的方式移动,这是我对javascript的理解(尽管还不多)。我必须做大量的研究,但我一事无成
我试着让我的游戏角色,在玩家的级别,移动。但是,它不会随着我的箭头键移动。控制台正在从我的函数接收日志,但角色没有移动
JS转储:
const canvas = document.getElementById('Game-Screen');
const ctx = canvas.getContext('2d');
canvas.width = 1200;
canvas.height = 900;
class Player {
constructor(x, y, radius, speed, x_velocity, y_velocity, forward) {
this.x = x;
this.y = y;
this.radius = radius;
this.speed = speed;
this.x_velocity = x_velocity;
this.y_velocity = y_velocity;
this.forward = forward = true;
}
Appear() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
};
controls = {
right: false,
left: false,
up: false,
keyEvent: function(pressed) {
let keyCondition = (pressed.type == 'keydown') ? true : false;
console.log(keyCondition);
switch (pressed.keyCode) {
case 37: //will go left
controls.left = keyCondition;
break;
case 38: //will go up
controls.up = keyCondition;
break;
case 39: // will go down
controls.right = keyCondition;
break;
}
}
};
const movement = function() {
if (controls.up && Ship.forward == false) {
Ship.y_velocity -= 20;
Ship.forward = true;
}
if (controls.left) {
Ship.x_velocity -= 0.5;
}
if (controls.right) {
Ship.x_velocity += 0.5;
}
controls.y_velocity += 1.5;
controls.x += controls.x_velocity;
controls.y += controls.y_velocity;
controls.x_velocity += 0.9;
controls.y_velocity += 0.9;
};
window.addEventListener('keydown', controls.keyEvent);
window.addEventListener('keyup', controls.keyEvent);
const Ship = new Player(550, 800, 25, 0, 0);
const Astroids = [];
Ship.Appear();
function update() {
this.x = this.x + this.x_velocity.x
this.y = this.y + this.y_velocity.y
}
class Astroider {
constructor(x, y, radius, speed, x_velocity, y_velocity, forward) {
this.x = x;
this.y = y;
this.radius = radius;
this.speed = speed;
this.x_velocity = x_velocity;
this.y_velocity = y_velocity;
this.forward = forward = true;
}
Appear() {
ctx.beginPath();
// x y
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
};
const Astro = new Astroider(600, 200, 40, 0, 0)
function spawnAstroids() {
setInterval(() => {
const x = 200
const y = 300
const radius = 40
const color = 'grey';
const velocity = {
x: 1,
y: 1
}
Astroid.push(new Astroider(x, y, radius, color, velocity))
}, 2000)
console.log(Astroid);
}
Astroid = [];
(pressed.type==“keydown”)?true:false可以缩短为pressed.type==“keydown”
您永远不会调用函数movement()
;这可能是个问题,我承认这有点不相关,但大写命名不是传统上为类保留的吗?欢迎来到StackOverflow。。。你有很多代码!如果问题只出在球员身上,你能把所有其他的东西都去掉,只专注于这一点,这有助于我们节省时间你应该读到:谢谢,谢谢Rojo和其他我不,它仍然与我的代码一起工作,虽然它可能会导致以后的问题,所以我改变它。