gpt4 book ai didi

JavaScript 让球移动

转载 作者:行者123 更新时间:2023-11-28 04:12:04 25 4
gpt4 key购买 nike

我试图在按空格时让球移动,但我似乎不知道该怎么做。

它是带有 createjs 库的普通 Javascript。有人可以帮助我并给我一点提示吗?

window.addEventListener('load', preload);
var canvas = document.getElementById('myCanvas');

var stage, queue;
var ball;
var paddle;
var settings = {
lives: 3,
points: 0,
speed: 3,
ballMovingSpeed: 7
}
var fingerDown = false;
var keys = {
left: false,
right: false,
shoot: false
}
var ballSettings = {
ballRadius: 10,
dx: 2,
dy: -2
}
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;



function preload() {
"use strict";
stage = new createjs.Stage("myCanvas");
queue = new createjs.LoadQueue(true);
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", tickHappened);
drawPaddle();
drawBall();
window.addEventListener('keydown', keyDown);
window.addEventListener('keyup', keyUp);
}



function drawBall() {
"use strict"
ball = new createjs.Shape();
ball.graphics.beginFill('red').drawCircle(0, 0, 10);
stage.addChild(ball);
ball.x = 400;
ball.y = 535;
canvasHeight += ballSettings.dy;
canvasWidth += ballSettings.dx;

}

// paddle Movement
//--------------------------------*

function keyDown(e) {
"use strict";
console.log(e.keyCode);
switch (e.keyCode) {
case 37:
keys.left = true;
break;
case 39:
keys.right = true;
break;
case 32:
keys.shoot = true;
break;
}
}

function keyUp(e) {
"use strict";
switch (e.keyCode) {
case 37:
keys.left = false;
break;
case 39:
keys.right = false;
break;
case 32:
keys.shoot = false;
break;
}
}


function movePaddle() {
"use strict";
if (keys.left) {
paddle.x -= settings.speed;
if (paddle.x < 0 + paddle.regX) {
paddle.x = 0 + paddle.regX;
}
} else if (keys.right) {
paddle.x += settings.speed;
if (paddle.x > canvasWidth - paddle.width + paddle.regX) {
paddle.x = canvasWidth - paddle.width + paddle.regX;
}
} else if (keys.shoot) {
console.log("shoot ball");
if (canvasWidth + ballSettings.dx > canvas.width - ballSettings.ballRadius || canvasWidth + ballSettings.dx < ballSettings.ballRadius) {
ballSettings.dx = -ballSettings.dx;
}
if (canvasHeight + ballSettings.dy > canvas.height - ballSettings.ballRadius || canvasHeight + ballSettings.dy < ballSettings.ballRadius) {
ballSettings.dy = -ballSettings.dy;
}
}
}

function tickHappened(e) {
"use strict";
movePaddle();
stage.update(e);
}

最佳答案

所以为了让你的物体移动,你需要一些东西。首先,您需要重新绘制它,您似乎已将其设置为每秒重新绘制60次。接下来,您必须更新对象的位置。你的球需要两个东西,一个速度 X 和一个速度 Y。每次刻度,你将设置 ball.x += ball.velX 以便每次它都会随着它的移动速度移动它的位置,并且一旦它击中某物,只需设置 ball.velX = -ball.velX。

我不确定您正在从事什么项目,但我假设它有点类似于乒乓球,如果您想查看或使用我在自己的乒乓球游戏中使用的一些代码,请随意 - http://pongio.bitballoon.com/

关于JavaScript 让球移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46183462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com