我正在寻求实现一个类似行星的系统,其中你有大的、大部分固定的物体,周围有很多较小的物体。这个想法是,较小的物体可以围绕较大的物体运行,但也会改变它们围绕哪些较大的物体运行。我试图在较小的物体上使用牛顿行为类型,但它使那些较小的物体试图绕着一切运行,而不仅仅是大物体。有没有办法在一组对象上定义行为(我将它们放在一个数组中)并让它们只被另一组对象中的对象吸引?
为了给你一个直观的想法,这就是它目前的样子(https://i.imgur.com/DqizSFO.png):
我希望橙色物体绕蓝色物体运行,但我不希望橙色或蓝色物体分别被其他橙色或蓝色物体吸引。PhysicsJS可以做到这一点吗?
这是我目前的进展。要查看运行中的脚本,请在 CodePen 上查看):
var magnets = []
var particles = []
function rand (from, to) {
return Math.floor(Math.random() * to) + from
}
function generateMagnet (world, renderer) {
var magnet = Physics.body('circle', {
x: rand(0, renderer.width),
y: rand(0, renderer.height),
radius: 50,
mass: 2,
vx: 0.001,
vy: 0.001,
treatment: 'static',
styles: {
fillStyle: '#6c71c4'
}
})
magnets.push(magnet)
world.add(magnet)
}
function generateParticle (world, renderer) {
var particle = Physics.body('circle', {
x: rand(0, renderer.width),
y: rand(0, renderer.height),
vx: rand(-100, 100) / 1000,
vy: rand(-100, 100) / 1000,
mass: 1,
radius: 5,
styles: {
fillStyle: '#cb4b16'
}
})
particles.push(particle)
world.add(particle)
}
Physics(function (world) {
// bounds of the window
var el = document.getElementById('matterContainer')
var viewportBounds = Physics.aabb(0, 0, el.scrollWidth, el.scrollHeight)
var edgeBounce
var renderer
// create a renderer
renderer = Physics.renderer('canvas', {
'el': el
})
el.childNodes[0].style.left = 0
// add the renderer
world.add(renderer)
// render on each step
world.on('step', function () {
world.render()
})
// varrain objects to these bounds
edgeBounce = Physics.behavior('edge-collision-detection', {
aabb: viewportBounds,
restitution: 0.99,
cof: 0.8
})
// resize events
window.addEventListener('resize', function () {
// as of 0.7.0 the renderer will auto resize... so we just take the values from the renderer
viewportBounds = Physics.aabb(0, 0, renderer.width, renderer.height)
// update the boundaries
edgeBounce.setAABB(viewportBounds)
}, true)
for (var i = 0; i < 5; i++) generateMagnet(world, renderer)
for (var i = 0; i < 100; i++) generateParticle(world, renderer)
// add things to the world
var newton = Physics.behavior('newtonian', { strength: 0.05 })
// newton.applyTo(particles)
var attractor = Physics.behavior('attractor', {
order: 0,
strength: 0.1
}).applyTo(magnets);
world.add([
Physics.behavior('body-impulse-response'),
newton,
edgeBounce
])
// subscribe to ticker to advance the simulation
Physics.util.ticker.on(function (time) {
world.step(time)
})
})
<script src="http://wellcaffeinated.net/PhysicsJS/assets/scripts/vendor/physicsjs-current/physicsjs-full.min.js"></script>
<section id="matterContainer" class="sct-HomepageHero pt-0 pb-0"></section>
<style>
.sct-HomepageHero.pt-0.pb-0 {
min-height: 600px;
padding-top: 0;
padding-bottom: 0;
}
</style>