Передвижение бота в игре

Рейтинг: -1Ответов: 1Опубликовано: 04.04.2015

Ребяят, вообщем я делаю игру, и мне надо чтоб бот шел к определенной точке, с этим проблем нет, но вот когда он идет(и когда доходит), то он начинает трястись вот код:

var canvas, ctx;

var girls = {
x: 0,
y: 0,
newX: 0,
newY: 0,
width: 50,
height: 50,
newWay: false,

/*updateWay: function() {
    this.newX = Math.round(Math.random() * 550);
    this.newY = Math.round(Math.random() * 450);
},*/

update: function() {
    this.x = this.x < this.newX ? this.x += 3 : this.x -= 3;
    this.y = this.y < this.newY ? this.y += 3 : this.y -= 3;
},

  render: function() {
    ctx.strokeStyle = "pink";
    ctx.strokeRect(this.x, this.y, this.width, this.height);
  }
};

function init() {
  canvas = document.createElement("canvas");
  canvas.width = 600;
  canvas.height = 500;

  ctx = canvas.getContext("2d");
  document.body.appendChild(canvas);

  player.x = (canvas.width - player.width)/2;
  player.y = (canvas.height - player.height)/2;

  girls.newX = Math.round(Math.random() * 550);
  girls.newY = Math.round(Math.random() * 450);

  console.log(girls.newX + " | " + girls.newY);

  var loop = function() {
     update();
     render();
  };
   setInterval(loop, 1000/60);
  }

  function update() {
     girls.update();
  }

  function render() {
    ctx.clearRect(0,0,canvas.width, canvas.height);
    girls.render();
  }

  init();

Ответы

▲ 1

this.x = this.x < this.newX ? this.x += 3 : this.x -= 3;

this.y = this.y < this.newY ? this.y += 3 : this.y -= 3;

Знаешь что делает тернарный оператор? Если точка меньше нужной, то к ней добавляется 3, а если нет (или они равны) - вычитается. Я не рекомендовал бы использовать его в таких сложных случаях, тем более что в будущем код движения наверняка вырастет. Делай вот так

if (this.x < this.newX) this.x += 3;
if (this.x > this.newX) this.x -= 3;

if (this.y < this.newY) this.y += 3;
if (this.y > this.newY) this.y -= 3;