如何在p5.js中实现围绕偏心点旋转多个图像

问题描述

我正在使用JavaScript和p5.js库制作塔防游戏。我有2张图片,分别是 base gun 。喷枪被拉到底座的顶部,以使其看起来像一个整体。我需要我的枪对准敌人(沿着一条路径)。我需要帮助使喷枪在一个点(而不是中心)上旋转,请记住,其中可能有多个塔。我已经尝试过平移(以更改中心)和旋转,但这对许多对象不起作用,并且显然无法跟踪许多对象。

关于此事,我也没有看到任何其他问题,是否有更好的解决方案/替代方法解决我要解决的问题?


必需的代码


一些重要变量

var isFiretowerpressed = false;    // checks if tower is placed
var FiretowerPos = [];    // location of every tower => [] - 2d array

预载的东西

function preload() {
    backgroundImg = loadImage("http://127.0.0.1:8080/img/extra/map1.png");
    [...]
    firetowerbaseImg = loadImage("http://127.0.0.1:8080/img/towers/firetowerbase.png");
    firetowerturretImg = loadImage("http://127.0.0.1:8080/img/towers/firetowergun.png");

}

绘制每帧

function draw() 
{

    background(60,238,161);
    [...]
    if (isFiretowerpressed == true)    //checks if I have pressed the button to place the tower
    {
        image(firetowerbaseImg,mouseX - 28,mouseY - 28);
        // show range circle
        noFill();
        stroke(0,0);
        strokeWeight(1);
        circle(mouseX,mouseY,300);
    }
    for (var i = 0; i < FiretowerPos.length; i++) 
    {
        image(firetowerbaseImg,FiretowerPos[i][0],FiretowerPos[i][1]);
        image(firetowerturretImg,FiretowerPos[i][1]-20);

    }

}

鼠标单击事件

function mouseClicked()
{

    if (isFiretowerpressed==true && mouseX+28 <= 750) // place-able area
    {
        FiretowerPos.push([mouseX-28,mouseY-28]);
        isFiretowerpressed = false;
    }
}

图片显示了我正在使用的2张图片(底座和枪支)。我需要能够将枪旋向敌人

Picture to help visualize problem

感谢您的帮助,谢谢

解决方法

如果您还使用p5库中的push()pop()方法,则可以平移和旋转多个对象,这些方法允许您存储当前设置。 / p>

要旋转到给定点,功能atan2(y2 - y1,x2 - x1)是常用的方法。

为说明起见,我编写了此快速摘要,其中只有当鼠标在枪支的范围内时,枪支才会朝着鼠标旋转。

let gunSprite

function preload(){
  gunSprite = loadImage("https://i.imgur.com/ayvg9J2.jpg",()=>{
    gunSprite.resize(20,40)
  })
}

let guns = [
  { x: 160,y: 80,angle: 0,range: 100 },{ x: 300,y: 200,range: 150 },{ x: 100,y: 240,range: 120 }
]

function setup(){
  createCanvas(600,400)
  noFill()
}

function draw(){
  background(200)
  for(let gun of guns)
      drawGun(gun)
}

function drawGun(gun){
  
  const isWithinRange = dist(mouseX,mouseY,gun.x,gun.y) < gun.range
  if(isWithinRange)
    gun.angle = atan2(mouseY - gun.y,mouseX - gun.x) + radians(90)
  
  push()
    translate(gun.x,gun.y)
    rect(-25,-20,50,40) // Draw the gun base
    ellipse(0,gun.range*2) // display the gun range
    rotate(gun.angle)
    image(gunSprite,-10,-40) // Set the offset of the gun sprite and draw the gun
  pop()
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js"></script>