How to move characters with mouse?

Asked

Viewed 164 times

6

I am developing a hobby (browser game), where the user will guide his plane through the scenery!

I have 2 div, at first I create a rectangle where when moving the mouse I capture the axis X and Y, I need to move a character in the second div with a certain delay in relation to the position X of the first.

Example, if the position X is = a 60 the character moves in the same position (X - 25) and position Y = Y.

Based on other research: Jsfiddle

1 answer

7


An example of a line of reasoning to be used,

$(function() {

  var $location = $('#location');
  var $move = $('#target > span');
  var $area = $('#area');
  
  var Localizacao = function (e) {
    
    var x = e.clientX;
    var y = e.clientY;
    var coor = "Coordenadas: (" + "x: " + x + "," + "y: " + y + ")";

    $area.html(coor);
    $move.stop().animate({
      left: x + 'px',
      top: y + 'px',
    },50);

  };

  var clearCoor = function() {
    document.getElementById("area").innerHTML = "   ";
  };

  $location.on({
    mousemove: Localizacao,
    mouseleave: clearCoor
  });
  
});
* { margin: 0; padding: 0; line-height: 1; }
div { width: 200px; height: 100px; border: 1px solid black; position: relative; }
div > span { position: absolute; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="location"></div>
<p id="area"></p>
<div id="target">
  <span>+</span>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.