简体   繁体   English

p5.j​​s-使用翻译时的冲突检测

[英]p5.js - collision detection while using translate

I'm having a problem I can't seem to solve when using the p5 javascript library. 使用p5 javascript库时,我似乎无法解决问题。 Essentially I want to create a random "snake" of circles in p5.js. 本质上,我想在p5.js中创建一个随机的圆圈“蛇”。

My code looks like this. 我的代码如下所示。

function setup() {
 createCanvas(400, 400)
  background(220)
  noFill()
  noLoop()
}

function draw() {
  translate(200,200)
  strokeWeight(1)
  for(j=0;j<5;j++) {
        snake() 
  }
}

function snake() {
  rad = 10
  ellipse(0,0,rad,rad)
  push()
  for(i=0;i<100;i++) {
    a = random(0,360)
    translate(rad*sin(a),rad*cos(a))
    ellipse(0,0,rad,rad)
  }
  pop()
}

What I do is create a circle in the centre, then select a random point 360 degrees around that circle at a certain radius from it, and create a new circle there. 我要做的是在中心创建一个圆,然后在该圆周围以一定半径选择一个随机点360度,然后在其中创建一个新圆。 Then I translate the centre point (the 0,0) to the centre of that new circle and start the process again. 然后,我将中心点(0,0)平移到该新圆的中心,然后再次开始该过程。

That delivers a snake, but the problem is the circles inevitably start overlapping. 那是一条蛇,但问题是圈子不可避免地开始重叠。

What I want to do is have my code check whether a randomly created new circle will overlap with any of the previous ones, and if it does, select a new location for that circle. 我想做的是让我的代码检查随机创建的新圆是否会与任何先前的圆重叠,如果有,请为该圆选择一个新位置。

All the approaches to overlap detection in p5.js I encountered so far, however, use distance to calculate whether circles overlap. 到目前为止,我在p5.js中遇到的所有重叠检测方法都使用距离来计算圆是否重叠。 Which of course the use of translate messes up. 当然使用哪种翻译会搞砸。

So if anyone has a solution for my problem, feel free to let me know. 因此,如果有人对我的问题有解决方案,请随时告诉我。

You need to store the positions and sizes of the circles in some kind of data structure, like an array. 您需要将圆的位置和大小存储在某些类型的数据结构,像数组。 Then check against those circles before you create a new one. 然后在创建新的圈子之前,先对这些圈子进行检查。

You might be able to do this using the translate() function, but if I were you I would instead do the translation myself. 你也许可以做到这一点使用translate()函数,但如果我是你,我反而做翻译我自己。 Instead of using the translate() function, keep track of the circle X and circle Y, and move that point as you draw new circles. 除了使用的translate()函数,跟踪圆X和圈Y和在绘制新的循环往复这一点。

This will allow you to work in screen coordinates, which will make it easier to do collision detection . 这将使您能够处理屏幕坐标,这将使碰撞检测更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM