简体   繁体   中英

How can I change the position of an element when it is touched by another element in javascript?

I'm new to JavaScript and I'm trying to create a game just like this in javascript: http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/ . Except I'm not allowed to use the canvas element so the code I use doesn't seem to work. The problem I'm having is getting my mouse/food element to move to a random new position when the snake/slither element collides with the mouse/food element. I'm also generally not sure if my update() function is working and if it isn't I don't know why.

I've tried a lot of different ways to get the code to execute correctly; placing the update function in different places like window onload,in each arrow function, etc. I tried sourcing many other codes but all I can find is people who use the canvas element to create their game.

 var snake = null; var slither = document.querySelector("#snake > .snake"); var mouse = document.querySelector("#food > .mouse"); var body = document.getElementById("grass"); x = body.width / 2; y = body.height / 2; function init() { snake = document.getElementById("snake"); snake.style.position = 'relative'; snake.style.left = '0px'; snake.style.top = '0px'; } function getKeyAndMove(e) { var key_code = e.which || e.keyCode; switch (key_code) { case 37: //left arrow key moveLeft(); break; case 38: //Up arrow key moveUp(); break; case 39: //right arrow key moveRight(); break; case 40: //down arrow key moveDown(); break; } } function moveLeft() { snake.style.left = parseInt(snake.style.left) - 7 + 'px'; update(); } function moveUp() { snake.style.top = parseInt(snake.style.top) - 7 + 'px'; update(); } function moveRight() { snake.style.left = parseInt(snake.style.left) + 7 + 'px'; update(); } function moveDown() { snake.style.top = parseInt(snake.style.top) + 7 + 'px'; update(); } window.onload = init; var update = () => { if ( mouse.x === slither.x || mouse.y === slither.y || mouse.y === slither.y && mouse.x === slither.x ) { mouse.x = Math.floor((Math.random() * 30) + 1); mouse.y = Math.floor((Math.random() * 30) + 1); } };
 <body id="grass" onkeydown='getKeyAndMove(event)'> <div id="snake"> <img class="snake" src="img/snek.png" alt="snake"> </div> <div id="food"> <img class="mouse" src="img/mouse.png" alt="mouse"> </div> <script type="text/javascript" src="myscript.js"></script> </body>

I need answers only in JavaScript please because I haven't learned JQuery and all that yet. I think there could be a problem with my x and y values but I don't know how to set the position of the mouse to move to relative to the window like they do in the canvas element examples. I'm just confused, please help.

Your collision detection needs works because you are currently only checking whether the left and top sides intersect, but there are many more combinations.

Look at this answer and this for more

I also changed the selector to move the div that holds the mouse the same way that you had defined for your snake. I also set it to be position = 'relative'; so that it can move around. I added 'px' to the end of your random coord string

 var snake = null; var food = null; var slither = document.querySelector("#snake > .snake"); var mouse = document.querySelector("#food > .mouse"); var body = document.getElementById("grass"); x = body.width / 2; y = body.height / 2; function init() { snake = document.getElementById("snake"); snake.style.position = 'relative'; snake.style.left = '0px'; snake.style.top = '0px'; food = document.getElementById("food"); food.style.position = 'relative'; } function getKeyAndMove(e) { var key_code = e.which || e.keyCode; switch (key_code) { case 37: //left arrow key moveLeft(); break; case 38: //Up arrow key moveUp(); break; case 39: //right arrow key moveRight(); break; case 40: //down arrow key moveDown(); break; } } function moveLeft() { snake.style.left = parseInt(snake.style.left) - 7 + 'px'; update(); } function moveUp() { snake.style.top = parseInt(snake.style.top) - 7 + 'px'; update(); } function moveRight() { snake.style.left = parseInt(snake.style.left) + 7 + 'px'; update(); } function moveDown() { snake.style.top = parseInt(snake.style.top) + 7 + 'px'; update(); } window.onload = init; var update = () => { if ( mouse.x === slither.x || mouse.y === slither.y || mouse.y === slither.y && mouse.x === slither.x ) { food.style.left = Math.floor((Math.random() * 30) + 1) + "px"; food.style.right = Math.floor((Math.random() * 30) + 1) + "px"; } };
 <body id="grass" onkeydown='getKeyAndMove(event)'> <div id="snake"> <img class="snake" src="img/snek.png" alt="snake"> </div> <div id="food"> <img class="mouse" src="img/mouse.png" alt="mouse"> </div> <script type="text/javascript" src="myscript.js"></script> </body>

This code is untested but may get you started...

function collisionCheck(elem1, elem2) {
    var elem1Bounds = elem1.getBoundingClientRect();
    var elem2Bounds = elem2.getBoundingClientRect();

    var elem1Center = {
      x: elem1Bounds.left + (elem1Bounds.width / 2),
      y: elem1Bounds.top + (elem1Bounds.height / 2)
    }

    var elem2Center = {
      x: elem2Bounds.left + (elem2Bounds.width / 2),
      y: elem2Bounds.top + (elem2Bounds.height / 2)
    }

    // initialize if element 1 is within the viewport
    if (
        elem1Bounds.top >= 0 &&
        elem1Bounds.left >= 0 &&
        elem1Bounds.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        elem1Bounds.right <= (window.innerWidth || document.documentElement.clientWidth)
    ) {

      // see https://stackoverflow.com/a/17628488/2116041
      var distance = Math.sqrt(
        Math.pow(elem1Bounds.x - elem2Bounds.x, 2) + 
        Math.pow(elem1Bounds.y - elem2Bounds.y, 2) 
      );

      if (distance > elem1Bounds.width && distance > elem1Bounds.height) {
        // no collision
        return false; 
      } else {
        // collision detected!
        return true; 
      }
    }
};

here's the answer I ended up with. I'm still tweaking some css stuff n all but this code does what I want it to :). Also the positioning of the elements were the reason it wasn't staying in the window. I still have the rest of the code, this is just the important bits. Thanks for the help!

function init() {
    snake = document.getElementById("snake");
    snake.style.position = 'relative';
    snake.style.left = '0px';
    snake.style.top = '0px';
    food = document.getElementById("food");
    food.style.position = 'absolute';
}




function collisionCheck(slither, mouse) {
    var snakeBounds = slither.getBoundingClientRect();
    var mouseBounds = mouse.getBoundingClientRect();

    if (!((snakeBounds.top + snakeBounds.height) < mouseBounds.top ||
        snakeBounds.top > (mouseBounds.height + mouseBounds.top) ||
        (snakeBounds.left + snakeBounds.width) < mouseBounds.left ||
        snakeBounds.left > (mouseBounds.width + mouseBounds.left))) {

        food.style.left = Math.floor(Math.random() * 800) + 'px';  
        food.style.top = Math.floor(Math.random() * 500) + 'px';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM