#javascript #canvas
#javascript #холст
Вопрос:
Я делаю простой и простой космический шутер. JS
HTML
Я подумал, что было бы здорово повернуть проигрыватель (rect) нажатием клавиш E
или Q
.
ничего сложного, верно?
итак, я создал canvas и player как объект со своими функциями. одной из его функций является поворот (направление), прямо сейчас он должен вращаться на 45 градусов, но этого не происходит.
в любом случае, вот код :
(спасибо за помощь)
const canvas = document.createElement("canvas");
let body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
const ctx = canvas.getContext("2d");
canvas.width = innerWidth;
canvas.height = innerHeight;
canvas.style.backgroundColor = "black";
canvas.innerHTML = "your browser does not support HTML5! Please upgrade";
window.addEventListener("resize", () => {
canvas.width = innerWidth;
canvas.height = innerHeight;
});
let qPressed = false,ePressed = false;
const player = {
x:canvas.width/2-25,
y:canvas.height/2-25,
w:50,
h:50,
score:0,
hp : 100,
create : function(){
ctx.fillStyle = "pink";
ctx.fillRect(this.x,this.y,this.w,this.h);
},
holdInScreen : function(){
if (this.x < 0) {
this.x = canvas.width;
} else if (this.x - 50 > canvas.width) {
this.x = 0;
} else if (this.y < 0) {
this.y = canvas.height;
} else if (this.y > canvas.height) {
this.y = 0;
}
},
rotate : function(direction){
if(direction == "left"){
ctx.save();
ctx.translate(this.x this.w, this.y);
ctx.rotate(Math.PI / 4);
ctx.restore();
}else{
}
},
keyHandler : function(){
if(ePressed){
this.rotate("right");
}else if(qPressed){
this.rotate("left");
}
},
giveScore : function(){
return this.score;
},
getHit : function(){
if(this.hp <= 0){
console.log("game over!");
}else{
this.hp -= 25;
}
},
update:function(){
this.holdInScreen();
this.keyHandler();
}
}
const update = function(){
player.update();
}
const render = function(){
player.create();
}
let id;
const Loop = function(){
id = requestAnimationFrame(Loop);
update();
ctx.clearRect(0,0,canvas.width,canvas.height);
render();
}
Loop()
window.addEventListener("keydown", (e) => {
if(e.keyCode == 69) ePressed = true;
if(e.keyCode == 81) qPressed = true;
})
window.addEventListener("keyup", (e) => {
if(e.keyCode == 69) ePressed = true;
if(e.keyCode == 81) qPressed = true;
})
Ответ №1:
const canvas = document.createElement("canvas");
let body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
const ctx = canvas.getContext("2d");
canvas.width = innerWidth - 20;
canvas.height = innerHeight - 20;
canvas.style.backgroundColor = "black";
canvas.innerHTML = "your browser does not support HTML5! Please upgrade";
window.addEventListener("resize", () => {
canvas.width = innerWidth - 40;
canvas.height = innerHeight - 40;
});
let qPressed = false,ePressed = false;
const player = {
x:canvas.width/2-25,
y:canvas.height/2-25,
w:50,
h:50,
angle: 0,
score:0,
hp : 100,
create(){
ctx.save();
// Translate coords to the center of square..
ctx.translate(this.x this.w/2, this.y this.h/2);
// Rotate..
ctx.rotate(this.angle);
// Fill..
ctx.fillStyle = "pink";
// Remember coords are translated
ctx.fillRect(-this.w/2, -this.h/2, this.w, this.h);
ctx.restore();
},
holdInScreen : function(){
if (this.x < 0) {
this.x = canvas.width;
} else if (this.x - 50 > canvas.width) {
this.x = 0;
} else if (this.y < 0) {
this.y = canvas.height;
} else if (this.y > canvas.height) {
this.y = 0;
}
},
rotate(direction) {
// Dont draw anything here, just change the angle
if(direction == "left") {
this.angle = .02;
}else{
this.angle -= .02;
}
},
keyHandler(){
if(ePressed){
this.rotate("right");
}else if(qPressed){
this.rotate("left");
}
},
giveScore(){
return this.score;
},
getHit(){
if(this.hp <= 0){
console.log("game over!");
}else{
this.hp -= 25;
}
},
update(){
this.holdInScreen();
this.keyHandler();
}
}
const Loop = function(){
player.update();
ctx.clearRect(0,0,canvas.width,canvas.height);
player.create();
requestAnimationFrame(Loop);
}
Loop();
window.addEventListener("keydown", (e) => {
if(e.keyCode == 69) ePressed = true;
if(e.keyCode == 81) qPressed = true;
})
window.addEventListener("keyup", (e) => {
if(e.keyCode == 69) ePressed = false;
if(e.keyCode == 81) qPressed = false;
})
Ответ №2:
create: function () {
ctx.fillStyle = "pink";
ctx.fillRect(this.x, this.y, this.w, this.h);
},
rotate: function (direction) {
if (direction == "left") {
ctx.save();
ctx.translate(this.x this.w, this.y);
ctx.rotate(Math.PI / 4);
ctx.restore();
} else {
}
},
Вам нужно повернуть холст, а затем нарисовать проигрыватель.
В данный момент вы
- поворот холста и сброс контекста
- рисование проигрывателя
Когда на самом деле это должно быть
- переведите холст туда, где вы хотите, чтобы был объект
- поворот холста
- нарисуйте проигрыватель
Слегка отредактировал ваш код и удалил прослушиватель keyup.
const canvas = document.createElement("canvas");
let body = document.getElementsByTagName("body")[0];
body.appendChild(canvas);
const ctx = canvas.getContext("2d");
canvas.width = innerWidth;
canvas.height = innerHeight;
canvas.style.backgroundColor = "black";
canvas.innerHTML = "your browser does not support HTML5! Please upgrade";
window.addEventListener("resize", () => {
canvas.width = innerWidth;
canvas.height = innerHeight;
});
const player = {
x: canvas.width / 2 - 25,
y: canvas.height / 2 - 25,
w: 50,
h: 50,
score: 0,
hp: 100,
rotation: 0,
// Originally our create() function changed the name
drawPlayer: function () {
ctx.fillStyle = "pink";
ctx.save();
// Translate to center
ctx.translate(this.x this.w/2, this.y this.h/2);
// Rotate canvas based on rotation value
ctx.rotate(this.rotation * Math.PI / 180);
// Draw square
ctx.fillRect(-this.w/2, -this.h/2, this.w, this.h);
ctx.restore();
},
// Pressing 'q' or 'e' would result in updating the rotation
rotate: function (direction) {
if (direction === 'left') {
console.log('left');
this.rotation -= 45;
} else if (direction === 'right') {
console.log('right');
this.rotation = 45;
}
},
}
let id;
const Loop = function () {
id = requestAnimationFrame(Loop);
ctx.clearRect(0, 0, canvas.width, canvas.height);
player.drawPlayer();
}
Loop()
// Updated to call player rotate without the need to check for flags
document.addEventListener("keydown", (e) => {
console.log(e.keyCode);
switch (e.keyCode) {
case 69:
console.log('key right');
player.rotate("right");
break;
case 81:
console.log('key left');
player.rotate("left");
break;
default:
// Do nothing for other keys
break;
}
})
Комментарии:
1. Спасибо за объяснение и за помощь