0
\$\begingroup\$

I'm checking if the objects are too far from the player to be able to disable some things, I'm doing so:

const obj1 = {
     x: 0,
     y: 0
};

const player = {
   x: 0,
   y: 0
};

const sqrMagnitude = (x, y) => {
    return (x * x + y * y);
};

const isAwayFromPlayer = (entity, targetEntity, distanceMax) => {
    if(sqrMagnitude((targetEntity.x - entity.x), (targetEntity.y - 
entity.y)) > distanceMax * distanceMax){
        console.log("yes!");
    }else{
        console.log("no!");
    }
};

awayFromPlayer(obj1, player, 250);

but when walking with the player, sometimes I approach the objects and I get the console.log("yes!"), sometimes I move away and also I get, but it was only to work if I were away from them, I'm forgetting to do some conversion to absolute value with Math.abs for example? I remember that this is how it was when I needed some time ago, but something is not working properly.

\$\endgroup\$
  • \$\begingroup\$ You don't need abs() because the square already takes care of that i.e. the result of x*x is always positive. I'm not very familiar with arrow notation, but I don't see anything wrong with the code above. Are you certain that the console log is coming from the object you're close to and not another object far away? How are you calculating targetEntity and entity position? \$\endgroup\$ – Kyy13 Aug 22 '18 at 14:01
  • \$\begingroup\$ @Kyy13 x and y are the position of the canvas of the objects, I have to, I deactivate the drawing of the objects and when I close they stop being drawn. \$\endgroup\$ – PerduGames Aug 22 '18 at 14:04
  • \$\begingroup\$ You still need to post the code of how this is being called. When the check is being done is as important as the check itself. Minimum, Complete and Verifiable Example \$\endgroup\$ – Stephan Aug 22 '18 at 15:14
  • \$\begingroup\$ @Stephan I updated the question. \$\endgroup\$ – PerduGames Aug 22 '18 at 17:46
  • \$\begingroup\$ I cannot use your example to reproduce the error, so it is impossible to help you--but I can tell you that your method of checking the distance is correct. \$\endgroup\$ – Kyy13 Aug 23 '18 at 12:15
1
\$\begingroup\$

I made a playable demo below that does what you want:

// Create canvas, set it's dimensions, and get it's rendering context
var canvas = document.createElement('canvas');
var width = 520;
var height = 250;
canvas.width = width;
canvas.height = height;
var cx = canvas.getContext('2d');
cx.imageSmoothingEnabled = false;

// Add to DOM
document.body.appendChild(canvas);

//Get the h1 we'll show when you are near the enemy
var h1 = document.querySelector('h1');

// Player and enemy objects
var player = new GameObject(43, 43);
var enemy = new GameObject(Math.round(width / 2), Math.round(height / 2));
// The enemy's radius, at which point we know that the player is within range
enemy.radius = 43;

// Add on key down event listener for player object.
window.onkeydown = function(event) {
  switch (event.keyCode) {
    // Right
    case 39:
      event.preventDefault();
      player.pos.x += 7;
      break;
      // Up
    case 38:
      event.preventDefault();
      player.pos.y -= 7;
      break;
      // Left
    case 37:
      event.preventDefault();
      player.pos.x -= 7;
      break;
      // Down
    case 40:
      player.pos.y += 7;
      event.preventDefault();
      break;
  }
};

// Game functions

function Vect2(x, y, parent) {
  this.x = x || 0;
  this.y = y || 0;
  this.parent = parent;

  this.getDistance = function(vector) {
    //console.log(Math.round( Math.sqrt( Math.pow(this.x - vector.x, 2) + Math.pow(this.y - vector.y, 2) ) ));
    // Get the distance and round it.
    return Math.round(Math.sqrt(Math.pow(this.x - vector.pos.x, 2) + Math.pow(this.y - vector.pos.y, 2)));
  };
}

function GameObject(x, y) {
  this.pos = new Vect2(x, y, this);
  this.width = 25;
  this.height = 25;
  this.halfWidth = Math.round(this.width / 2);
  this.halfHeight = Math.round(this.height / 2);
  this.render = function() {
    cx.fillRect(this.pos.x - this.halfWidth, this.pos.y - this.halfHeight, this.width, this.height);
  };
  this.update = function() {};
}

// Naive loop
function loop() {
  update();
  render();

  requestAnimationFrame(loop);
}

function update() {
  player.update();
  enemy.update();

  // If the player is within the enemy's range, show message
  if (enemy.pos.getDistance(player) < enemy.radius) {
    h1.style = "visibility: visible;";
  } else {
    h1.style = "visibility: hidden;";
  }
}

function render() {
  cx.clearRect(0, 0, width, height);
  player.render();
  enemy.render();

  // Draw a circle around the enemy
  cx.beginPath();
  cx.arc(enemy.pos.x, enemy.pos.y, enemy.radius, 0, Math.PI * 2);
  cx.stroke();
  cx.closePath();
  // Draw a dot in the middle of player so that you know where on the player the check is ocurring
  cx.beginPath();
  cx.arc(player.pos.x, player.pos.y, 1, 0, Math.PI * 2);
  cx.fillStyle = 'blue';
  cx.fill();
  cx.fillStyle = 'black';
  cx.closePath();
}

loop();
html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

h1 {
  /*display: none;*/
}

canvas {
  border: 1px solid black;
}
<h1>Aha! Something's close</h1>

So the game checks if the player is within range of the enemy, and if so, it shows a message. I hope this was helpful

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.