gpt4 book ai didi

javascript - 在为第二个图像创建文字对象后,如何使用 WASD 键移动第二个图像

转载 作者:行者123 更新时间:2023-12-01 01:16:43 25 4
gpt4 key购买 nike

我正在尝试学习使用 WASD 键移动第二个对象,但我找不到详细说明其操作方法的具体信息。我在调整大小时也遇到了麻烦。我目前正在探索这款游戏,以尽我所能地学习。 https://jsfiddle.net/t2mjc5k1/ <===代码贴在下面。

我尝试了一些在网上看到的预先编写的 JavaScript 片段。我正在使用我在 StackOverflow 上找到的一个。我也一直在使用此网站 (https://keycode.info/) 来更好地了解事件键码的工作原理。

    // Arrow key codes
var UP = 38,
DOWN = 40,
RIGHT = 39,
LEFT = 37;
//wasd keycodes

/*var W = 87,
A = 65,
S = 83,
D = 68;*/

// rocket object
var rocket = {
img: document.querySelector("#rocket"),
x: 490,
y: 390,
width: 100
};

var UFO = {
img: document.querySelector("#ufo"),
x: 300,
y: 200,
width: 200 // Need to read up on x,y positioning.S
};

//sound array
var sounds = ["#Photon", "#Shrapnel"];

var currentSound = null;

const velocity = 8;

let torpedo = document.querySelector("#torpedo"),
startBtn = document.querySelector("#start"),
fireBtn = document.querySelector("#fire"),
ufo = document.querySelector("#ufo");


// Initialize objects on the screen
render ( );


/*
function startGameHandler( ) {
"use strict"
// Hide the intro screen, show the game screen
introScreen.style.display = "none";
gameScreen.style.display = "block";
rocket.img.style.display = "block";
ufo.style.display = "block";
}
*/

const startGameHandler = ( ) => {
"use strict";
// Hide the intro screen, show the game screen
introScreen.style.display = "none";
gameScreen.style.display = "block";
rocket.img.style.display = "block";
ufo.style.display = "block";
};

function fireTorpedoHandler( ) {
"use strict"
// Fire the photon torpedo!
// CSS animation occurs whenever torpedo
// 'left' property changes value
torpedo.style.visibility = "visible";
torpedo.style.left = (rocket.x - 200)+ "px";
}



const keydownHandler = event => {
"use strict"
if (event.keyCode == UP) {
rocket.y -= velocity;
}
if (event.keyCode == LEFT) {
rocket.x -= velocity;
}
if (event.keyCode === DOWN) {
rocket.y += velocity;
}
if (event.keyCode == RIGHT) {
rocket.x += velocity;
}

render( );
}


//moving the UFO
(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();


function onKeyDown(event) {
var keyCode = event.keyCode;
switch (keyCode) {
case 68: //d
keyD = true;
break;
case 83: //s
keyS = true;
break;
case 65: //a
keyA = true;
break;
case 87: //w
keyW = true;
break;
}
}

function onKeyUp(event) {
var keyCode = event.keyCode;

switch (keyCode) {
case 68: //d
keyD = false;
break;
case 83: //s
keyS = false;
break;
case 65: //a
keyA = false;
break;
case 87: //w
keyW = false;
break;
}
}

//neccessary variables
var clickX = 10;
var clickY = 10;

var keyW = false;
var keyA = false;
var keyS = false;
var keyD = false;

//main animation function
function ufoBooster() {
window.requestAnimationFrame(ufoBooster);
var canvas = document.getElementById("ufo");

if (keyD == true) {
clickX += 1;
}
if (keyS == true) {
clickY += 1;
}
if (keyA == true) {
clickX--;
}
if (keyW == true) {
clickY--;
}
}
window.requestAnimationFrame(ufoBooster);

// Moved here to get the arrow function to work.
startBtn.addEventListener("click",startGameHandler,false);
fireBtn.addEventListener("click",fireTorpedoHandler,false)
window.addEventListener("keydown",keydownHandler,false);

//ufo event listeners
window.addEventListener("keydown", onKeyDown, false);
window.addEventListener("keyup", onKeyUp, false);



function render( ) {
"use strict"

// position objects on the screen
rocket.img.style.left = rocket.x + "px";
rocket.img.style.top = rocket.y + "px";
torpedo.style.left = (rocket.x +10) + "px";
torpedo.style.top = (rocket.y+8) + "px";
torpedo.style.visibility = "hidden";



}
    * { margin: 0; 
padding: 0;
}

@font-face {
font-family: 'spaceAge';
src: url('../fonts/space_age-webfont.eot');
src: url('../fonts/space_age-webfont.eot?#iefix') format('embedded-opentype'),
url('../fonts/space_age-webfont.woff') format('woff'),
url('../fonts/space_age-webfont.ttf') format('truetype'),
url('../fonts/space_age-webfont.svg#space_ageregular') format('svg');
font-weight: normal;
font-style: normal;
}

#introScreen {
margin: 50px auto;
padding: 50px 30px;
width: 540px;
height: 350px;
position: relative;
background-color: #0d152a;
font-family: Arial, Helvetica, sans-serif;
color: white;
}
#title {
font-size: 32px;
line-height: 1.1em;
font-family: spaceAge;
}
#introScreen img {
float: left;
margin-right: 20px;
}
#introScreen h3 {
clear: both;
font-family: spaceAge;
margin-top: 40px;
}
#introScreen div {
margin-top: 40px;
text-align: center;
}

button {
font-family: spaceAge;
font-size: 150%;
padding: 4px 8px;
cursor: pointer;
color: white;

-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;

background: -webkit-linear-gradient(top, #a3a3a3, #000);
background: -moz-linear-gradient(top, #a3a3a3, #000);
background: linear-gradient(top, #a3a3a3, #000);

-webkit-box-shadow: 0px 5px 8px 3px rgba(255,255,255,0.3);
-moz-box-shadow: 0px 5px 8px 3px rgba(255,255,255,0.3);
box-shadow: 0px 5px 8px 3px rgba(255,255,255,0.3);
}
button:hover {
background: -webkit-linear-gradient(top, #acc7a3, #506651);
background: -moz-linear-gradient(top, #acc7a3, #506651);
background: linear-gradient(top, #acc7a3, #506651);
}
#gameScreen {
margin: 50px auto;
width: 600px;
height: 450px;
background-image: url("../images/bkg.jpg");
display:none;
position: relative;
}
#rocket {
position: absolute;
display: none;
}
#torpedo {
position: absolute;

/* transition */
-webkit-transition: left 0.5s ease-out 0s;
-moz-transition: left 0.5s ease-out 0s;
transition: left 0.5s ease-out 0s;
}
#ufo {
position: absolute;
display: none;

}
#gameUI {
width: 560px;
height: 50px;
padding: 10px 20px;
background-color: rgba(0,0,0,0.5);
color: white;
font-family: spaceAge;
line-height: 1em;
}
#gameInfo {
width: 450px;
height: 120px;
font-size: 120%;
float: left;
}
#gameControls {
width: 50px;
height: 55px;
padding-top: 5px;
float:left;
}
    <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Space Arcade</title>
<link rel="stylesheet" href="css/styles.css">
</head>

<body>
<section id="introScreen">
<img src="images/introImage.jpg" alt="intro image">
<span id="title">Big<br>Space<br>Sprite<br>Mover</span>
<h3>How to play:</h3>
<p>Use the arrow keys to move the rocket ship up, down, left, or right. Hit the <strong>Fire!</strong> button to fire a photon torpedo.</p>
<div>
<button id="start">Engage!</button>
</div>
</section>

<section id="gameScreen">
<div id="gameUI">
<div id="gameInfo">
<p>Dilithium fuel: 100%</p>
<p>Phasers: 25</p>
<p>Photon torpedoes: 10</p>
</div>
<div id="gameControls">
<button type= button id="fire" >Fire!</button>
</div>
</div>

<!-- absolutely positioned elements -->
<img id="ufo" src="images/ufo.png" alt="UFO">
<img id="torpedo" src="images/torpedo.png" alt="torpedo">
<img id="rocket" src="images/rocket.png" alt="Rocket Ship sprite">
</section>


<!--<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="photon.mp3" ></audio>-->



<audio id="Photon">
<source src="Photon.mp3" type="audio/mp3">
<source src="Photon.ogg" type="audio/ogg">
</audio>

<audio id="Shrapnel">
<source src="Shrapnel.mp3" type="audio/mp3">
<source s`enter code here`rc="Shrapnel.ogg" type="audio/ogg">
</audio>

<script src="js/program.js"></script>
</body>
</html>

我想学习使用 WASD 键移动 ufo 图像。火箭图像当前绑定(bind)到箭头键。

最佳答案

您好,游戏开发人员(看起来是这样),您为什么不使用 canvas 或其他库(如 PixiJS)?

无论如何,我喜欢的做法是为控件创建单独的对象并检查按键是否按下:

对象/变量

//Controls
var controls = {
"ufo":
{
"left":[65, 74], //A/J
"right":[68, 76], //D/L
"up":[87, 73], //W/I
"down":[83, 75] //S/K
}

"rocket":{
"left":[37], //LEFT
"right":[39], //RIGHT
"up":[38], //UP
"down":[40] //DOWN
},

"pause":[80], //P
"mute":[77] //M
};

//Is Key down?
//For eg, if the W (87) key is down, isKeyDown[87] will be true, otherwise, false.
var isKeyDown = {};

//To Set:
for(var i in controls)
if(controls.hasOwnProperty(i))
if(i=="rocket" || i=="ufo"){ //special cases where we have nested objects
for(var j in controls[i]){
for(var k=0;j<controls[i][j].length;k++)
isKeyDown[controls[i][j][k]] = false;
}
}
else for(var j=0;j<controls[i].length;j++)
isKeyDown[controls[i][j]] = false;

对于可扩展性非常有利:您可以包含用于暂停和静音等其他操作的按钮按下操作。您还可以通过多个按键来完成相同的操作(例如,我为您添加了 WASD 和 IJKL,这样两个现在都可以移动 UFO)。

事件监听器

window.addEventListener("keydown", function (e) {
for(i in isKeyDown)
if(isKeyDown.hasOwnProperty(i) && e.keyCode == i)
isKeyDown[e.keyCode] = true;
}, false);

window.addEventListener("keyup", function (e) {
if(isKeyDown[e.keyCode] != undefined)
isKeyDown[e.keyCode] = false;
else return;

//Actual movements can be handled elsewhere in your tick/main animation function (see below)

//Pausing and muting (just in case you want them):
for(var j=0;j<controls["pause"].length;j++)
if(e.keyCode==controls["pause"][j]){
//PAUSE GAME
break;
}

for(var j=0;j<controls["mute"].length;j++)
if(e.keyCode==controls["mute"][j]){
//MUTE GAME
break;
}
}, false);

在你的刻度/动画函数中 //对于运动。进入您的主要刻度/动画功能

var movements = {
"ufo":{
"up":false,
"down":false,
"right":false,
"left":false
},
"rocket":{
"up":false,
"down":false,
"right":false,
"left":false
}
};

//Rocket
for(var i in controls["rocket"])
if(controls.hasOwnProperty(i))
for(var j=0;j<controls["rocket"][i].length;j++){
if(isKeyDown[controls["rocket"][i][j]])
movements["rocket"][i] = true;
}

//UFO
for(var i in controls["ufo"])
if(controls.hasOwnProperty(i))
for(var j=0;j<controls["ufo"][i].length;j++){
if(isKeyDown[controls["ufo"][i][j]])
movements["ufo"][i] = true;
}

实际运动

//Actual movements, also to go into your tick function or equivalent handler:

//Rocket
if (event.keyCode == movements["rocket"]["up"]) {
rocket.y -= velocity;
}
if (event.keyCode == movements["rocket"]["left"]) {
rocket.x -= velocity;
}
if (event.keyCode === movements["rocket"]["down"]) {
rocket.y += velocity;
}
if (event.keyCode == movements["rocket"]["right"]) {
rocket.x += velocity;
}

//UFO
if (event.keyCode == movements["ufo"]["up"]) {
UFO.y -= velocity;
}
if (event.keyCode == movements["ufo"]["left"]) {
UFO.x -= velocity;
}
if (event.keyCode === movements["ufo"]["down"]) {
UFO.y += velocity;
}
if (event.keyCode == movements["ufo"]["right"]) {
UFO.x += velocity;
}

虽然之前的用户已经“回答”了你的问题,但我相信,当你的游戏规模越来越大、功能越来越多时,这种方法会更加有用。

关于javascript - 在为第二个图像创建文字对象后,如何使用 WASD 键移动第二个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54682507/

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