How to get the X and Y coordinates of the image that I am moving around the canvas

When I move the player.hero image around the canvas, I need a variable containing the current x and y pos of the hero. Therefore, I can turn the image of a zombie into the current position of the hero. Thanks, and if my code is still terrible, suggest corrections.

(function() {

    var canvas, context, width, height, speed = 8;    
    var interval_id;
    var zombies = [];
    var bullets = [];

    var moveLeft = false;
    var moveRight = false;
    var moveUp = false;
    var moveDown = false;

    var player = {
        x : 0,
        y : 0,
        width : 35,
        height : 60,
        hero : new Image(),
    };

    for (var i = 0; i < 10; i += 1){
        var zombie = {
            x : 10,
            y : 10,
            undead : new Image(),
            targetToGox : 0,
            targetToGoy : 0,
         };
         zombies.push(zombie);
    }
    var mouse = {
        x : 0,
        y : 0,
    }

    document.addEventListener('DOMContentLoaded', init, false);

    function init() {    
        canvas = document.querySelector('canvas');
        context = canvas.getContext('2d');
        width = canvas.width;
        height = canvas.height;
        player.x = width / 2 - 18;
        player.y = height / 2 - 30;
        player.hero.src = 'hero.png';
        zombie.undead.src = 'zombie.png';
        //context.drawImage(player.hero, player.x, player.y);  
        window.addEventListener("keydown", activate,false);
        window.addEventListener("keyup",deactivate,false);
        //window.addEventListener("mouseover", drawImagePointingAt, false);
        interval_player = window.setInterval(drawPlayer, 33);
    }

    function drawPlayer() {
        context.clearRect(0 ,0 ,width, height);
        context.drawImage(player.hero,player.x, player.y);
        //******** need zombie to go to position of player.hero******///
        context.drawImage(zombie.undead (somthing for x and y coordinats of player.hero);
        // stops player moveing beyond the bounds of the canvas
        if (player.x + player.width >= width) {
            moveRight = false
        }
        if (player.y + player.height >= height) {
            moveDown = false
        }
        if (player.x  <= 0) {
            moveLeft = false
        }
        if (player.y <= 0) {
            moveUp = false
        }     
        if (moveRight) {
            player.x  += speed;
        }
        if (moveUp) {
            player.y -= speed;
        }
        if (moveDown) {
            player.y += speed;
        }
        if (moveLeft){
            player.x -= speed;
        }

    function activate(event) {
        var keyCode = event.keyCode;
            if (keyCode === 87){
                moveUp = true;
            }
            else if (keyCode === 68){
                moveRight = true;
            }
            else if (keyCode === 83){
                moveDown = true;
            }
            else if (keyCode === 65){
                moveLeft = true;
            }

    }
    function deactivate(event) {
        var keyCode = event.keyCode;
            if (keyCode === 87){
                moveUp = false;}
            else if (keyCode === 68){
                moveRight = false;}
            else if (keyCode === 83){
                moveDown = false;}
            else if (keyCode === 65){
                moveLeft = false;}
    }
    function getRandomNumber(min, max) {
        return Math.round(Math.random() * (max - min)) + min;
    }
    function stop() {
        clearInterval(interval_player);

    }
})();
+4
source share
2 answers

I assume you mean this line?

//******** need zombie to go to position of player.hero******///
context.drawImage(zombie.undead (somthing for x and y coordinats of player.hero);

I would change the code to something like:

function init() {    
  ...
  interval_player = window.setInterval(updateGame, 33);
}

function updateGame() {
    context.clearRect(0 ,0 ,width, height);
    updatePlayer();
    for (let zombie of zombies) {
       updateZombie(zombie);
}

function updatePlayer() {
    // stops player moveing beyond the bounds of the canvas
    if (player.x + player.width >= width) {
        moveRight = false
    }
    if (player.y + player.height >= height) {
        moveDown = false
    }
    if (player.x  <= 0) {
        moveLeft = false
    }
    if (player.y <= 0) {
        moveUp = false
    }     
    if (moveRight) {
        player.x  += speed;
    }
    if (moveUp) {
        player.y -= speed;
    }
    if (moveDown) {
        player.y += speed;
    }
    if (moveLeft){
        player.x -= speed;
    }
    context.drawImage(player.x, player.y);
}

function updateZombie(zombie) {
  // Move zombie closer to player
  if (zombie.x > player.x)
     zombie.x -= zombieSpeed;
  else if (zombie.x < player.x)
     zombie.x += zombie.Speed;

  if (zombie.y > player.y)
     zombie.y -= zombieSpeed;
  else if (zombie.y < player.y)
     zombie.y += zombie.Speed;

  context.drawImage(zombie.undead, zombie.x, zombie.y);
}

This line is here:

zombie.undead.src = 'zombie.png';

only the last created zombie will change. You really need to move this:

for (var i = 0; i < 10; i += 1) {
    var zombie = {
        x : 10,
        y : 10,
        undead : new Image(),
        targetToGox : 0,
        targetToGoy : 0,
     };
     zombie.undead.src = 'zombie.png'; 
     zombies.push(zombie);
}
+1
source

, , , "... X Y , ".

script, , .

. , , , .

, ( ). , , , .

, , "", .

- . (), Player . , ( , Encapsulation ' 'Loose connection' ' '). , .

: .

, , , ( ). , , , , , , " ".

, moveLeft, " ", "", .

, "duplicate" . , Player Zombie , GameObject. GameObject "" Player Zombie ( , , )

, 20 , , , - . , , , , , - .

"" Javascript, , " " JS, - .

, jSL, Javascript 'class', , , , .

const ZOMBIE_COUNT = 10

function GameState() {
    this.player  = null;
    this.enemies = []
}
var Game = new GameState() // our global game state

// An abstract 'game object' or character
function GameObject({x, y, image}) {
    this.x = x
    this.y = y
    this.image = image
}
GameObject.prototype.draw = function() {
    Game.ctx.fillStyle = this.color
    Game.ctx.fillRect(this.x, this.y, 10, 10)
}
GameObject.prototype.moveLeft =  function(n) { if(this.x > 0) this.x -= n }
GameObject.prototype.moveRight = function(n) { if(this.x < Game.width) this.x += n }
GameObject.prototype.moveDown =  function(n) { if(this.y < Game.height) this.y += n}
GameObject.prototype.moveUp =    function(n) { if(this.y > 0) this.y -= n }

function Player({x, y, width}) {
    GameObject.call(this, {x, y}) // setup x, y & image
    this.color = 'red'
}
Player.prototype = Object.create(GameObject.prototype, {})

function Zombie({x, y, target}) {
    GameObject.call(this, {x, y}) // setup x, y & image
    this.target = target // target contains the player
    this.color = 'blue'
}
Zombie.prototype = Object.create(GameObject.prototype, {})
Zombie.prototype.moveToPlayer = function() {
    let {x, y} = Game.player
    // very basic 'movement' logic
    if (this.x < x) {
        this.moveRight(1/4)
    } else if (this.x > x) {
        this.moveLeft(1/4)
    }

    if (this.y > y) {
        this.moveUp(1/4)
    } else if (this.y < y) {
        this.moveDown(1/4)
    }
}


function init() {
    var canvas = document.getElementById('canvas')
    if (canvas.getContext) {
        var ctx = canvas.getContext('2d')
    } else {
        console.log("No canvas")
        return -1
    }

    let {width, height} = canvas

    // Setup our game object
    Game.width = width
    Game.height = height
    Game.ctx = ctx
    // Create our player in the middle
    Game.player = new Player({x: width / 2, y: height / 2})

    // Create our enemies
    for(let i = 0; i < ZOMBIE_COUNT; i++) {
        Game.enemies.push(new Zombie({x: Math.random() * width  | 0, // truncate our value
                                      y: Math.random() * height | 0}))
    }

    game_loop()
}

function game_loop() {
    window.requestAnimationFrame(game_loop)
    Game.ctx.fillStyle = 'white'
    Game.ctx.fillRect(0, 0, Game.width, Game.height);
    Game.player.draw()

    Game.enemies.map(enemy => {
        enemy.moveToPlayer()
        enemy.draw()
    })
}

function process_key(ev) {
    let speed = 3
    let key = ev.keyCode
    if (key === 68)
        Game.player.moveRight(speed)
    if (key === 87)
        Game.player.moveUp(speed)
    if (key === 65)
        Game.player.moveLeft(speed)
    if (key === 83)
        Game.player.moveDown(speed)
}

window.addEventListener('keydown', process_key, false);

init()
canvas { border: 3px solid #333; }
<canvas id="canvas" width="400" height="400"></canvas>
+2

Source: https://habr.com/ru/post/1672069/


All Articles