Сделайте объект пули в javascript p5.js - PullRequest
1 голос
/ 22 апреля 2019

я делал javascript-игру в p5.js. Я сделал большую часть игры, затем хотел добавить немного боя. Я сделал оружие, которое стреляет пулями. Но сейчас пулю сложно сделать. Вот как работает мое оружие:

  1. начинается с местоположения игрока
  2. определяет вращение y щелчка мыши (смотрит в центр экрана и смотрит, на какой угол поворота (360 градусов))
  3. смотрит на y вращение мыши
  4. уходит на расстоянии

Так как мне сделать пулю? У меня есть базовый сценарий, но пуля удаляется только тогда, когда она попадает в противника, только идет в мосе, имеет тупой алгоритм для поиска пути к мыши, вы можете иметь только одну пулю одновременно, и если она не поражает любые враги, он просто сидит на земле, как мина.

Вот код psuedo (вообще никаких правил программирования):

Make bullet(playerPositionX,playerPositionY,mouseX,mousey) as a object:
 starter x and y = playerPostionX and playerPositionY
 lookTowards a point(mouseX,mouseY)
 goto the point(mouseX and mouseY) from the starter X and Y
 movespeed is 20pixel per frame

Итак, вот что я получил в своей игре прямо сейчас: Сценарий эскиза:

var player;
var enemy;
var bullet;
var score = 0;
function setup(){
  createCanvas(600,600);
  player = new Player();
  enemy = new Enemy();
  textSize(20);
}
function draw(){
  clear();
  background(51);
  enemy.show();
  enemy.moveToPlayer(player.x, player.y);
  player.show();
  player.MovePlayer();
  if (bullet != undefined){
    bullet.show();
    bullet.toMouse();
    if (dist(bullet.x,bullet.y,enemy.x,enemy.y) <= enemy.r){
      enemy = new Enemy();
      score += 100;
      bullet = undefined;
    }
  }
  fill(255);
  text(score,500,500,100,100)
}
function mousePressed(){
  //if (enemy.clicked(mouseX,mouseY)){
  bullet = new Bullet(mouseX,mouseY,player.x,player.y);
  //enemy = new Enemy();
  //}
}

Сценарий пули:

function Bullet(X,Y,PX,PY){
  this.speed = 20;
  this.x = PX;
  this.y = PY;
  this.r = 5;
  this.show = function(){
    fill(255,255,0);
    stroke(128,128,0);
    circle(this.x,this.y,this.r);
  }
  this.toMouse = function(){
    if (Y < this.y){
      this.y += -1*this.speed;
    } else if (Y > this.y) {
      this.y += 1*this.speed;
    }
    if (X < this.x){
      this.x += -1*this.speed;
    } else if (X > this.x){
      this.x += 1*this.speed;
    }
  }

}

Вражеский сценарий:

function Enemy(){
  this.r = 25;
  this.x = 0+this.r;
  this.y = 0+this.r;
  this.chance = random(0,1);
  console.log(this.chance);
  if (this.chance <= 0.10){
    this.speed = 3;
    this.r = 15;
    this.red = 0;
    this.green = 0;
    this.blue = 255;
  } else {
    this.speed = 2;
    this.red = 255;
    this.green = 0;
    this.blue = 0;
  }
  this.show = function(){
    fill(this.red,this.green,this.blue);
    stroke(128,0,0);
    circle(this.x,this.y,this.r);
  }
  this.moveToPlayer = function(playerX,playerY){
    if (playerY < this.y){
      this.y += -1*this.speed;
    } else if (playerY > this.y) {
      this.y += 1*this.speed;
    }
    if (playerX < this.x){
      this.x += -1*this.speed;
    } else if (playerX > this.x){
      this.x += 1*this.speed;
    }
  }
  /*
  this.clicked = function(mX,mY){
    if (dist(mX,mY,this.x,this.y) <= this.r){
      return true;
    }
    return false;
  }
  */
}

Сценарий игрока:

function Player(){
  this.x = width/2;
  this.y = height/2;
  this.r = 20;
  this.speed = 4;
  this.show = function(){
    fill(0,255,0);
    stroke(0,128,0);
    circle(this.x,this.y,this.r);
  }
  this.moveY = function(number){
    this.y += (number*this.speed);
  }
  this.moveX = function(number){
    this.x += (number*this.speed);
  }
  this.MovePlayer = function(){
    if (keyIsDown(UP_ARROW)){
      if (this.y + (-1*20) > 0)
        this.moveY(-1);
    }
    if (keyIsDown(DOWN_ARROW)){
      if (this.y + (1*20) < height)
        this.moveY(1);
    }
    if (keyIsDown(LEFT_ARROW)){
      if (this.x + (-1*20) > 0)
        this.moveX(-1);
    }
    if (keyIsDown(RIGHT_ARROW)){
      if (this.x + (1*20) < width)
        this.moveX(1);
    }
  }
}

В html-файле есть все, что нужно Спасибо за продвижение!

var player;
var enemy;
var bullet;
var score = 0;
function setup(){
  createCanvas(600,600);
  player = new Player();
  enemy = new Enemy();
  textSize(20);
}
function draw(){
  clear();
  background(51);
  enemy.show();
  enemy.moveToPlayer(player.x, player.y);
  player.show();
  player.MovePlayer();
  if (bullet != undefined){
    bullet.show();
    bullet.toMouse();
    if (dist(bullet.x,bullet.y,enemy.x,enemy.y) <= enemy.r){
      enemy = new Enemy();
      score += 100;
      bullet = undefined;
    }
  }
  fill(255);
  text(score,500,500,100,100)
}
function mousePressed(){
  //if (enemy.clicked(mouseX,mouseY)){
  bullet = new Bullet(mouseX,mouseY,player.x,player.y);
  //enemy = new Enemy();
  //}
}

function Bullet(X,Y,PX,PY){
  this.speed = 20;
  this.x = PX;
  this.y = PY;
  this.r = 5;
  this.show = function(){
    fill(255,255,0);
    stroke(128,128,0);
    circle(this.x,this.y,this.r);
  }
  this.toMouse = function(){
    if (Y < this.y){
      this.y += -1*this.speed;
    } else if (Y > this.y) {
      this.y += 1*this.speed;
    }
    if (X < this.x){
      this.x += -1*this.speed;
    } else if (X > this.x){
      this.x += 1*this.speed;
    }
  }

}

function Enemy(){
  this.r = 25;
  this.x = 0+this.r;
  this.y = 0+this.r;
  this.chance = random(0,1);
  console.log(this.chance);
  if (this.chance <= 0.10){
    this.speed = 3;
    this.r = 15;
    this.red = 0;
    this.green = 0;
    this.blue = 255;
  } else {
    this.speed = 2;
    this.red = 255;
    this.green = 0;
    this.blue = 0;
  }
  this.show = function(){
    fill(this.red,this.green,this.blue);
    stroke(128,0,0);
    circle(this.x,this.y,this.r);
  }
  this.moveToPlayer = function(playerX,playerY){
    if (playerY < this.y){
      this.y += -1*this.speed;
    } else if (playerY > this.y) {
      this.y += 1*this.speed;
    }
    if (playerX < this.x){
      this.x += -1*this.speed;
    } else if (playerX > this.x){
      this.x += 1*this.speed;
    }
  }
  /*
  this.clicked = function(mX,mY){
    if (dist(mX,mY,this.x,this.y) <= this.r){
      return true;
    }
    return false;
  }
  */
}

function Player(){
  this.x = width/2;
  this.y = height/2;
  this.r = 20;
  this.speed = 4;
  this.show = function(){
    fill(0,255,0);
    stroke(0,128,0);
    circle(this.x,this.y,this.r);
  }
  this.moveY = function(number){
    this.y += (number*this.speed);
  }
  this.moveX = function(number){
    this.x += (number*this.speed);
  }
  this.MovePlayer = function(){
    if (keyIsDown(UP_ARROW)){
      if (this.y + (-1*20) > 0)
        this.moveY(-1);
    }
    if (keyIsDown(DOWN_ARROW)){
      if (this.y + (1*20) < height)
        this.moveY(1);
    }
    if (keyIsDown(LEFT_ARROW)){
      if (this.x + (-1*20) > 0)
        this.moveX(-1);
    }
    if (keyIsDown(RIGHT_ARROW)){
      if (this.x + (1*20) < width)
        this.moveX(1);
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>

1 Ответ

2 голосов
/ 22 апреля 2019

Создайте массив маркеров вместо одной и добавьте новый массив в массив, если нажата кнопка мыши:

var bullets = [];

function mousePressed(){
    if (mouseX != player.x || mouseY != player.y ) {
        bullets.push( new Bullet(mouseX,mouseY,player.x,player.y) )
    }
}

Используйте p5.Vector, чтобы вычислить нормализованное направление от позиции игрока к позиции мыши в классе [Bullet]. Это определяет направление перемещения Bullet, которое можно использовать в toMouse, чтобы обновить положение объекта Bullet.
Далее добавьте метод onScreen, который проверяет, находится ли Bullet в границах экрана:

function Bullet(X,Y,PX,PY){
    this.speed = 2;
    this.x = PX;
    this.y = PY;
    this.dir = createVector(X-PX, Y-PY).normalize()
    this.r = 5;

    this.show = function(){
      fill(255,255,0);
      stroke(128,128,0);
      circle(this.x,this.y,this.r);
    }
    this.toMouse = function() {
        this.x += this.dir.x * this.speed;
        this.y += this.dir.y * this.speed;
    }
    this.onScreen = function() {
      return this.x > -this.r && this.x < width+this.r &&
              this.y > -this.r && this.y < height+this.r;
    }
}

Пройдите через пули в draw. Проверьте, попала ли пуля враг или покинула экран. Сохраните оставшиеся пули для следующего запуска draw:

let keepbullets = []
let anyhit = false;
for (let i=0; i < bullets.length; ++ i) {
    bullets[i].toMouse();
    let hit = dist(bullets[i].x, bullets[i].y, enemy.x, enemy.y) <= enemy.r;
    anyhit = anyhit || hit
    if (!hit && bullets[i].onScreen()) {
        keepbullets.push(bullets[i]);
        bullets[i].show();
    }
}
bullets = keepbullets;
if (anyhit) {
    enemy = new Enemy();
    score += 100;
}

См. Пример, где я применил предложения к исходному коду из вопроса. Обратите внимание, что я значительно замедлил скорость пуль, чтобы сделать эффект нескольких пуль видимым:

var player;
var enemy;
var bullets = [];
var score = 0;
function setup(){
  createCanvas(600,600);
  player = new Player();
  enemy = new Enemy();
  textSize(20);
}
function draw(){
  clear();
  background(51);
  enemy.show();
  enemy.moveToPlayer(player.x, player.y);
  player.show();
  player.MovePlayer();

  let keepbullets = []
  let anyhit = false;
  for (let i=0; i < bullets.length; ++ i) {
      bullets[i].toMouse();
      let hit = dist(bullets[i].x, bullets[i].y, enemy.x, enemy.y) <= enemy.r;
      anyhit = anyhit || hit
      if (!hit && bullets[i].onScreen()) {
          keepbullets.push(bullets[i]);
          bullets[i].show();
      }
  }
  bullets = keepbullets;
  if (anyhit) {
      enemy = new Enemy();
      score += 100;
  }
  
  fill(255);
  text(score,500,500,100,100)
}

function mousePressed(){
    if (mouseX != player.x || mouseY != player.y ) {
        bullets.push( new Bullet(mouseX,mouseY,player.x,player.y) )
    }
}

function Bullet(X,Y,PX,PY){
    this.speed = 2;
    this.x = PX;
    this.y = PY;
    this.dir = createVector(X-PX, Y-PY).normalize()
    this.r = 5;
    
    this.show = function(){
      fill(255,255,0);
      stroke(128,128,0);
      circle(this.x,this.y,this.r);
    }
    this.toMouse = function() {
        this.x += this.dir.x * this.speed;
        this.y += this.dir.y * this.speed;
    }
    this.onScreen = function() {
      return this.x > -this.r && this.x < width+this.r &&
              this.y > -this.r && this.y < height+this.r;
    }
}

function Enemy(){
  this.r = 25;
  this.x = 0+this.r;
  this.y = 0+this.r;
  this.chance = random(0,1);
  console.log(this.chance);
  if (this.chance <= 0.10){
    this.speed = 3;
    this.r = 15;
    this.red = 0;
    this.green = 0;
    this.blue = 255;
  } else {
    this.speed = 2;
    this.red = 255;
    this.green = 0;
    this.blue = 0;
  }
  this.show = function(){
    fill(this.red,this.green,this.blue);
    stroke(128,0,0);
    circle(this.x,this.y,this.r);
  }
  this.moveToPlayer = function(playerX,playerY){
    if (playerY < this.y){
      this.y += -1*this.speed;
    } else if (playerY > this.y) {
      this.y += 1*this.speed;
    }
    if (playerX < this.x){
      this.x += -1*this.speed;
    } else if (playerX > this.x){
      this.x += 1*this.speed;
    }
  }
  /*
  this.clicked = function(mX,mY){
    if (dist(mX,mY,this.x,this.y) <= this.r){
      return true;
    }
    return false;
  }
  */
}

function Player(){
  this.x = width/2;
  this.y = height/2;
  this.r = 20;
  this.speed = 4;
  this.show = function(){
    fill(0,255,0);
    stroke(0,128,0);
    circle(this.x,this.y,this.r);
  }
  this.moveY = function(number){
    this.y += (number*this.speed);
  }
  this.moveX = function(number){
    this.x += (number*this.speed);
  }
  this.MovePlayer = function(){
    if (keyIsDown(UP_ARROW)){
      if (this.y + (-1*20) > 0)
        this.moveY(-1);
    }
    if (keyIsDown(DOWN_ARROW)){
      if (this.y + (1*20) < height)
        this.moveY(1);
    }
    if (keyIsDown(LEFT_ARROW)){
      if (this.x + (-1*20) > 0)
        this.moveX(-1);
    }
    if (keyIsDown(RIGHT_ARROW)){
      if (this.x + (1*20) < width)
        this.moveX(1);
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"></script>
...