Compare value of property of all instances of class in python - class

I'm trying to write an object oriented program (as a learning exercise, I know there may be simpler ways to do it) in which beads bounce around a 2D plane bounded by a ring. Each bead is an object defined by a class ball. In setting the initial positions of the balls I need to check that no other ball has already been placed at the same x and y coordinates.
#Class for the beads
class ball:
NumbBalls = 0
#Constructor
def __init__(self,Beads):
self.ball = sphere(pos = vector(0,0,0), radius = radiusBall,color=color.red)
ball.NumbBalls += 1
self.ball.pos = self.createInitialPosition(Beads)
#Assign ball its initial position
def createInitialPosition(self,other):
#CODE to compare self.ball.pos and other.ball.pos which returns a unique position coordinate
#Main program
NumbBeads = 100
Beads = []#Create empty list for all the beads
#create balls in random initial positions
Beads = [ball(Beads) for item in range(NumbBeads)]
I can get this to work if I create two objects bead1 and bead2 and then pass bead1 and bead2 as arguments ie bead2 = ball(bead1) but how do I do this if I am generating a list of beads and want all of them to be compared with self. Hopefully that makes sense.

Perhaps rather than the approach you are currently taking, you should consider something along these lines (of course, with the necessary changes to your class definition/methods):
N = 100
initialPositions = []
while len(initialPositions) <= N:
newPosition = generateRandomPosition()
if newPosition in initialPositions:
pass
else:
initialPositions.append(newPosition)
ballList = [ ball(p) for p in initialPositions ]
In other words, generate a list of initial positions outside of the creation of your objects, and do whatever validation/restriction you need during that creation. Then just create your objects from that list. If N is really large, you might want to consider a dictionary (or a mutable set of some sort) instead of a list for initialPositions, to help speed up the membership testing, but it's still the same concept...

Related

Confused about get_rays function in NeRF

I've been trying to understand NeRF. I finished reading the paper(Tancik) and watched some of the videos. I have been looking at some parts of the code. However, I can't quite wrap my head around what the get_rays function does in terms of the code. Could anybody just run through line-by-line about what each line in the the get_rays function is supposed to do?
def get_rays(H,W , focal, c2w): #c2w is pose
i, j = tf.meshgrid(tf.range(W, dtype=tf.float32), tf.range(H, dtype=tf.float32), indexing='xy')
dirs = tf.stack([(i-W*.5)/focal, -(j-H*.5)/focal, -tf.ones_like(i)], -1)
rays_d = tf.reduce_sum(dirs[..., np.newaxis, :] * c2w[:3,:3], -1)
rays_o = tf.broadcast_to(c2w[:3,-1], tf.shape(rays_d))
return rays_o, rays_d
It creates two lists, rays_o represents points where rays originate (camera centre) and rays_d represents direction vectors of each ray casting through the centre of every pixel of the camera. In this case, all values in the rays_o are the same because the function gets rays from a single camera.

Grouping (without collision), adding and removing multiple bodies and polygons in pymunk?

I'm using code from the pymunk index_video to create a generic function that creates multiple cars which race each other and if they reach the right extreme of the screen, they are removed from Space and re-generated on the left extreme of the screen.
The problem is, that in the example code, each part of the car (chassis, pin joint, motor, wheels) is added to Space separately. I wanted to treat the entire car as a single body whose coordinates I can keep track of by storing the reference of the entire car body in a List and add or delete it to the Space easily.
Also, if the wheels are too close to the chassis, they collide with each other. I presume using a ShapeFilter can help avoid such collisions, but for that I need all parts of the car as a single body.
Please bear with me. I'm completely new to this jargon.
def car(space):
pos = Vec2d(100,200)
wheel_color = 52,219,119
shovel_color = 219,119,52
mass = 100
radius = 25
moment = pymunk.moment_for_circle(mass, 20, radius)
wheel1_b = pymunk.Body(mass, moment)
wheel1_s = pymunk.Circle(wheel1_b, radius)
wheel1_s.friction = 1.5
wheel1_s.color = wheel_color
space.add(wheel1_b, wheel1_s)
mass = 100
radius = 25
moment = pymunk.moment_for_circle(mass, 20, radius)
wheel2_b = pymunk.Body(mass, moment)
wheel2_s = pymunk.Circle(wheel2_b, radius)
wheel2_s.friction = 1.5
wheel2_s.color = wheel_color
space.add(wheel2_b, wheel2_s)
mass = 100
size = (50,30)
moment = pymunk.moment_for_box(mass, size)
chassi_b = pymunk.Body(mass, moment)
chassi_s = pymunk.Poly.create_box(chassi_b, size)
space.add(chassi_b, chassi_s)
vs = [(0,0),(25,45),(0,45)]
shovel_s = pymunk.Poly(chassi_b, vs, transform = pymunk.Transform(tx=85))
shovel_s.friction = 0.5
shovel_s.color = shovel_color
space.add(shovel_s)
wheel1_b.position = pos - (55,0)
wheel2_b.position = pos + (55,0)
chassi_b.position = pos + (0,-25)
space.add(
pymunk.PinJoint(wheel1_b, chassi_b, (0,0), (-25,-15)),
pymunk.PinJoint(wheel1_b, chassi_b, (0,0), (-25, 15)),
pymunk.PinJoint(wheel2_b, chassi_b, (0,0), (25,-15)),
pymunk.PinJoint(wheel2_b, chassi_b, (0,0), (25, 15))
)
speed = 4
space.add(
pymunk.SimpleMotor(wheel1_b, chassi_b, speed),
pymunk.SimpleMotor(wheel2_b, chassi_b, speed)
)
So this question is actually two questions.
A. How to make a "car object" that consists of multiple parts
There is no built in support for this, you have keep track of it yourself.
One way to do it is to create a car class that contains all the parts of the car. Something like this (not complete code, you need to fill in the full car)
class Car():
def __init__(self, pos):
self.wheel_body = pymunk.Body()
self.wheel_shape = pymunk.Circle()
self.chassi_body = pymunk.Body()
self.chassi_shape = pymunk.Poly()
self.motor = pymunk.SimpleMotor(wheel_body, chassi_body, 0)
def add_to_space(self, space)
space.add(self.wheel_body, self.wheel_shape, self.chassi_body, self.chassi_shape, self.motor)
def set_speed(self, speed)
self.motor.rate = speed
def car_position(self)
return self.chassi_body.position
B. How to make parts of the car to not collide with each other
This is quite straight forward, just as you already found the ShapeFilter is the way to go. For each "car", create a ShapeFilter and set a unique non-zero group on it. Then set that ShapeFilter as the filter property on each shape that makes up the car. It doesnt matter if the shapes belong to the same body or not, any shape with a ShapeFilter with a group set will not collide to other shapes with the same group set.

How to add a set of sprites in a certain pattern

I'm making a game that has a player that goes up and down if you hold the screen. This is not the important part though.
What I need is to add ENEMIES, that come toward you.
I need to know how to add the ENEMIES in a couple of different patterns.
Like this:(LOOK AT THE COINS PATTERN, HOW CAN I ACHIEVE THIS?)
You could define a 2-dimensional array to indicate where a coin should be e.g.
var coinRow = [[Int]]()
coinRow.append([0,1,1,1,1,1,1,0]) // '0' means 'No coin here'
coinRow.append([1,1,1,1,1,1,1,1]) // '1' means 'put coin here'
coinRow.append([0,1,1,1,1,1,1,0])
Then treat each coin 'area' as a 3x8 grid so given a starting location of the bottom-left hand corner as (0,0), do the following:
let coinStart = CGPoint(0,0)
coinPos = coinStart
for row in 0...2 { // Iterate over all rows
for column in 0...7 { // and all columns
if coinRow[row][column] == 1 { // Should there be a coin here?
putCoin(at: coinPos) // yes - draw one
}
coinPos.x += coin.width + coinHorizontalSeparation // next coin location
}
coinPos.y += coin.height + coinVerticalSeparation // Position to next row
coinPos.x = coinStart.x // Reset position to start of row
}
You wouldn't actually start at (0,0), so set coinStart as required. If the groups of coins appear in a regular pattern, then you can calculate coinStart and make the code that generates a block of coins a function that you call, passing coinStart as a parameter.

World.QueryAABB giving incorrect results in libgdx

I'm trying to implement mouse selection for my game. When I QueryAABB it looks like it's treating objects much larger than they really are.
Here's what's going on in the image
The blue box is an actor containing a body that I'd like to select
The outline on the blue box is drawn by Box2DDebugRenderer
The mouse selects a region on the screen (white box), this is entirely graphical
The AABB is converted to meters and passed to QueryAABB
The callback was called for the blue box and turned it red
The green outline left behind is a separate body to check if my conversions were correct, this is not used for the actual selection process
It seems to be connected to my meter size, the larger it is, the more inaccurate the result is. At 1 meter = 1 pixel it works perfectly.
Meter conversions
val MetersToPixels = 160f
val PixelsToMeters = 1/MetersToPixels
def toMeters(n: Float) = n * PixelsToMeters
def toPixels(n: Float) = n * MetersToPixels
In the image I'm using MetersToPixels = 160f so the inaccuracy is more visible, but I really want MetersToPixels = 16f.
Relevant selection code
val x1 = selectPos.x
val y1 = selectPos.y
val x2 = getX
val y2 = getY + getHeight
val (l,r) =
if (x2 < x1)
(x2,x1)
else
(x1,x2)
val (b,t) =
if (y2 < y1)
(y2,y1)
else
(y1,y2)
world.QueryAABB(selectCallback, toMeters(l),toMeters(b), toMeters(r),toMeters(t))
This code is inside the act method of my CursorActor class. And selectPos represents the initial point where the use pressed down the left mouse button and getX and getY are Actor methods giving the current position. The next bit sorts them because they might be out of order. Then they are converted to meters because they are all in pixel units.
selectCallback: QueryCallback
override def reportFixture(fixture: Fixture): Boolean = {
fixture.getBody.getUserData match {
case selectable: Selectable =>
selected += selectable
true
case _ => true
}
}
Selectable is a trait that sets a boolean flag internally after the query which helps determines the color of the blue box. And selected is a mutable.HashSet[Selectable] defined inside of CursorActor.
Other things possibly worth noting
I'm new to libgdx and box2d.
The camera is scaled x2
My Box2DDebugRenderer uses the camera's combined matrix multiplied by MetersToPixels
From what I was able to gather, QueryAABB is naturally inaccurate for optimization. However, I've hit a roadblock with libgdx because it doesn't have any publicly visible function like b2testOverlap and from what I understand, there's no plan for there to be one any time soon.
I think my best solution would probably be to use jbox2d and pretend that libgdx's physics implementation doesn't exist.
Or as noone suggested I could add it to libgdx myself.
UPDATE
I decided to go with a simple solution of gathering the vertices from the fixture's shape and using com.badlogic.gdx.math.Intersector against the vertices of the selection. It works I guess. I may stop using QueryAABB all together if I decide to switch to using a sensor for the select box.

how to remove a box2d Fixture

I have a square barrier that has edges defined at run time based on where the user puts the position and rotation of my barrier.
b2BodyDef barrierBodyDef;
barrierBodyDef.type = b2_staticBody;
barrierBodyDef.position.Set(curBarrier
.position.x/PTM_RATIO, curBarrier.position.y/PTM_RATIO);
barrierBodyDef.userData = curBarrier;
b2Body *barrierBody;
barrierBody = _world->CreateBody(&barrierBodyDef);
b2EdgeShape barrierEdge;
b2FixtureDef barrierShapeDef;
barrierShapeDef.shape = &barrierEdge;
barrierShapeDef.friction = 1.0f;
barrierEdge.Set(b2Vec2((x1)/PTM_RATIO, (y1)/PTM_RATIO),
b2Vec2((x2)/PTM_RATIO, (y2)/PTM_RATIO));
barrierBody->CreateFixture(&barrierShapeDef);
barrierEdge.Set(b2Vec2((x2)/PTM_RATIO, (y2)/PTM_RATIO),
b2Vec2((x3)/PTM_RATIO, (y3)/PTM_RATIO));
barrierBody->CreateFixture(&barrierShapeDef);
barrierEdge.Set(b2Vec2((x3)/PTM_RATIO, (y3)/PTM_RATIO),
b2Vec2((x4)/PTM_RATIO, (y4)/PTM_RATIO));
barrierBody->CreateFixture(&barrierShapeDef);
barrierEdge.Set(b2Vec2((x4)/PTM_RATIO, (y4)/PTM_RATIO),
b2Vec2((x1)/PTM_RATIO, (y1)/PTM_RATIO));
barrierBody->CreateFixture(&barrierShapeDef);
I now want to delete these edges, so that the user can re-position the barrier.
How do I go about removing the edges between point x1,y1, -> x4,y4, so that they are immune to collisions.
I am a bit new to Box2D.
Keep the fixture when creating it (local var here for example, you should use an ivar):
b2Fixture* barrierFixture = barrierBody->CreateFixture(&barrierShapeDef);
And later destroy the fixture:
barrierBody->DestroyFixture(barrierFixture);
barrierFixture = nil;
You can also use the body's GetFixtureList() to iterate over fixtures.
What you can not do is to add or remove shapes from a fixture, or modify the shape's vertices. To remove a point from a body's shape, you'll have to destroy the fixture and replace it with a new one.
It is not necessary to recreate the entire body, in fact that can be problematic since you'll probably want to preserve the body's current state (not just position but also linear and angular velocities and perhaps other things too).