Answer the question
In order to leave comments, you need to log in
There is an object that moves with the keys in the canvas (canvas), you need to make borders so that it does not leave the canvas. js how?
var tank;
function init() {
audio = new Audio("audio/audio.mp3");
audio.play();
myGame = new Game();
tank2 = new Tank (100, 100, 20, 20, "red");
tank = new Tank(100, 100, 20, 20, "red");
myGame.start();
}
function Game() {
self = this;
this.canvas = document.getElementById('MyCanvas');
this.context = this.canvas.getContext('2d');
key = false;
self.start = function () {
console.log("in start function")
setInterval(self.update, 10);
window.addEventListener('keydown', function (e) {
self.key = e.keyCode;
});
window.addEventListener('keyup', function (e) {
self.key = false;
});
}
self.update = function () {
console.log("in update function");
self.clear();
tank.stepX = 0;
tank.stepY = 0;
tank2.stepX = 0;
tank2.stepY = 0;
if (self.key == 37) {
tank.stepX--;
tank.angle = -90;
}
if (self.key == 38) {
tank.stepY--;
tank.angle = 0;
}
if (self.key == 39) {
tank.stepX++;
tank.angle = 90;
}
if (self.key == 40) {
tank.stepY++;
tank.angle = 180;
}
//tank 2
if (self.key == 83) {
tank2.stepX--;
tank2.angle = -90;
}
if (self.key == 87) {
tank2.stepY--;
tank2.angle = 65;
}
if (self.key == 68) {
tank2.stepX++;
tank2.angle = 90;
}
if (self.key == 97) {
tank2.stepY++;
tank2.angle = 1072;
}
tank.draw();
tank.pos();
tank2.draw();
tank2.pos();
}
self.clear = function () {
self.context.clearRect(0, 0, self.canvas.width, self.canvas.height);
}
}
function Tank(x, y, width, height, color) {
this.width = width;
this.height = height;
this.stepX = 0;
this.stepY = 0;
this.angle = 0;
this.x = x;
this.y = y;
this.A = this.stepX--,this.stepY--;
//img create
this.img = new Image;
this.img.src = ("img/tanchik.png");
this.img.width = 30;
this.img.height = 30;
this.ima = new Image;
this.ima.src = ("img/tank.png");
//new position tank
this.pos = function () {
this.x += this.stepX;
this.y += this.stepY;
}
this.draw = function () {
this.rotateTank(this.img,this.x, this.y, this.angle,this.img.width, this.img.height);
}
this.rotateTank = function (image, x, y, angle, width, height) {
TO_RADIANS = Math.PI / 180;
myGame.context.save();
myGame.context.translate(x, y);
myGame.context.rotate(angle * TO_RADIANS);
//myGame.context.drawImage(,-(width / 2), -(height / 2), width, height);
myGame.context.drawImage(image, -(width / 2), -(height / 2), width, height);
myGame.context.restore();
}
}
Answer the question
In order to leave comments, you need to log in
var clamp = function(val, min, max) {
return Math.min(Math.max(val, min), max);
}
// ...
// new position tank
this.pos = function () {
this.x += this.stepX;
this.y += this.stepY;
this.x = clamp(this.x, 0, canvas.width);
this.y = clamp(this.y, 0, canvas.height);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question