Cocos2d make physics body passable by anything - cocos2d-x

I'm trying to make a static physics body that can be passed by anything like it isn't there (like an ordinary sprite). Infinite restitution doesn't work apparently. Is this possible?
I'm trying to simulate climbing a ladder so I need to handle the contact while also making the ladder passable by the player body.

If you use Chipmunk (default physics in Cocos2d-x):
in the object A's physics initializer
// Chipmunk collision
int a = 1;// 0000 0001
physicsBody->setCategoryBitmask(a);
in the object B's physics initializer
int b = 0;// 0000 0000
physicsBody->setCollisionBitmask(b);// a & b will == 0 => no collision.
//
int c = 1;// 0000 0001
physicsBody->setContactTestBitmask(c);
// a & c will != 0 => will call onContact...() help you handle manually

Related

Julia scoping: why does this function modify a global variable?

I'm a relative newcomer to Julia, and so far I am a fan of it. But coming from years of R programming, some scoping rules leave me perplexed.
Let's take this function. This behaves exactly as I would expect.
function foo1(x)
y = x
t = 1
while t < 1000
t += 1
y += 1
end
return 42
end
var = 0;
foo1(var)
# 42
var
# 0
But when doing something similar on an array, it acts as a mutating function (modifies it argument in the global scope!)
function foo2(x)
y = x
t = 1
while t < 1000
t += 1
y[1] += 1
end
return 42
end
var = zeros(1);
foo2(var)
# 42
var
# 999.0
I realize I can fix this by changing the first line to y = copy(x) , but what is the reason for such a (dangerous?) behaviour in the first place?
I would write an answer to this, but I think John Myles White has already done it better than I ever could so I'll just link to his blogpost:
https://www.juliabloggers.com/values-vs-bindings-the-map-is-not-the-territory-3/
In short x = 1 and x[1] = 1 are very different operations. The first one is assignment—i.e. changing a binding of the variable x—while the second is a syntactic sugar for calling the setindex! function, which, in the case of arrays, assigns to a location in the array. Assignment only changes which variables refer to which objects and never modifies any objects. Mutation only modifies objects and never changes which variables refer to which objects. This answer has a bit more detail about the distinction: Creating copies in Julia with = operator.

Converting Arduino compass signal to useable heading

Background
I bought an Arduino magnetometer/compass with a QMC5883 chip from Amazon, however the bearing output I'm getting doesn't tally with the calculations I've found online. The serial output seems to be plausible (sinusoids with a phase difference of 90°), but the numbers I'm getting for the calculated bearing don't match what they are supposed to. I stored the serial output as a .csv file to graph the magnetometer response when turned through 360° in Excel:
Response was roughly as expected - Z remaining roughly steady (apart from a few wobbles caused by the cable!), X and Y varying sinusoidaly through 360°. (Bear in mind I couldn't turn the magnetometer at a constant speed with my hand which is why the curves are so unsteady).
However below is the graph of what heading was calculated; results were supposed to be between -180° and +180°:
As you can see it only varies around -60° to -160°, and each bearing reading is not unique as it is given by two different rotations of the magnetometer. The specific calculation in the code used (in full at the bottom) is:
bearing =180*atan2(y,x)/3.141592654; //values will range from +180 to -180°
bearing +=0-(19/60); //Adjust for local magnetic declination
Question
I can't figure out what's wrong with the calculation as it is used in a few different sources, and I would like to know how to convert the readings I'm getting to a usable range which is one to one instead of many to one, such as -180° to +180° or 0° to 360°.
Here is the code:
//There are several differences between the QMC5883L and the HMC5883L chips
//Differences in address: 0x0D for QMC5883L; 0x1E for HMC5883L
//Differences in register map (compare datasheets)
//Output data register differences include location of x,y,z and MSB and LSB for these parameters
//Control registers are also different (so location and values for settings change)
#include <Wire.h> //I2C Arduino Library
#define addr 0x0D //I2C Address for The QMC5883L (0x1E for HMC5883)
double scale=1.0;
void setup() {
// double scaleValues[9]={0.00,0.73,0.92,1.22,1.52,2.27,2.56,3.03,4.35};
// scale=scaleValues[2];
//initialize serial and I2C communications
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(addr); //start talking to slave
Wire.write(0x0B);
Wire.write(0x01);
Wire.endTransmission();
Wire.beginTransmission(addr); //start talking to slave
Wire.write(0x09);
Wire.write(0x1D);
Wire.endTransmission();
}
void loop() {
int x, y, z; //triple axis data
//Tell the QMC what regist to begin writing data into
Wire.beginTransmission(addr);
Wire.write(0x00); //start with register 00H for QMC5883L
Wire.endTransmission();
double bearing=0.00;
//Read the data.. 2, 8 bit bytes for each axis.. 6 total bytes
Wire.requestFrom(addr, 6);
//read 6 registers in order; register location (i.e.00H)indexes by one once read
if (6 <= Wire.available()) {
//note the order of following statements matters
//as each register will be read in sequence starting from data register 00H to 05H
//where order is xLSB,xMSB,yLSB,yMSB,zLSB,zMSB
//this is different from HMC5883L!
//data registers are 03 to 08
//where order is xMSB,xLSB,zMSB,zLSB,yMSB,yLSB
x = Wire.read(); //LSB x;
x |= Wire.read()<<8; //MSB x; bitshift left 8, then bitwise OR to make "x"
// x*=scale;
y = Wire.read(); //LSB y
y |= Wire.read()<<8; //MSB y;
// y*=scale;
z = Wire.read(); //LSB z; irrelevant for compass
z |= Wire.read()<<8; //MSB z;
// z*=scale;
bearing =180*atan2(y,x)/3.141592654;//values will range from +180 to -180 degrees
bearing +=0-(19/60);//Adjust for local magnetic declination
}
// Show Values
//Serial.print("X:");
Serial.print(x);
//Serial.print(" Y: ");
Serial.print(",");
Serial.print(y);
//Serial.print(" Z: ");
Serial.print(",");
Serial.print(z);
//Serial.print(" B: ");
Serial.print(",");
Serial.println(bearing);
delay(500);
}
For others reading this question:
The OP forgot to implement a x,y,z smoothing and an out of scope value removal. How this can be achieved and how its done look into the source code of this QMC5883 compass library:
QMC5883L Compass is an Arduino library for using QMC5583L series chip boards as a compass.
It supports:
Getting values of XYZ axis.
Calculating Azimuth.
Getting 16 point Azimuth bearing direction (0 - 15).
Getting 16 point Azimuth bearing Names (N, NNE, NE, ENE, E, ESE, SE, SSE, S, SSW, SW, WSW, W, WNW, NW, NNW)
Smoothing of XYZ readings via rolling averaging and min / max removal.

Libgdx Box2D fixtures that are both sensors and non sensors?

Let's say I have Bodies A, B, and C each with one fixture. It is possible to have fixtures A and B interact with each other with one or both being a sensor so no physics interaction occurs, but have both A and B have physics interactions with fixture C? So, A-B = no interaction, A-C = interaction, B-C = interaction
You should look into collision filtering (masking)
By setting up categories and masks for different objects you can control which ones are allowed to interact with each other.
// create categories
final short A = 0x0001; // 0000000000000001 in binary
final short B = 0x0002; // 0000000000000010 in binary
final short C = 0x0004; // 0000000000000100 in binary
// create masks
final short AM = 0x0006 // 0000000000000110 in binary
final short BM = 0x0006 // 0000000000000110 in binary
final short CM = 0x0001 // 0000000000000001 in binary
// apply masks and categories to fixtures
FixtureDef ADef = new FixtureDef();
ADef.filter.categoryBits = A;
ADef.filter.maskBits = AM;
Yes, this is possible using mask bits and category bits. These allow fixtures to only interact with certain other fixtures defined using these bits.
Category bits define the fixtures type, the default being 0.
Mask bits define which categories of fixtures the fixture can interact with.
So, for A and B to interact with C but not with each other, we need to apply the following category bits:
A.filter.categoryBits = 0x0001; //binary: 01
B.filter.categoryBits = 0x0001; //binary: 01
C.filter.categoryBits = 0x0002; //binary: 10
And the following mask bits:
A.filter.maskBits = 0x0002; //binary: 10
B.filter.maskBits = 0x0002; //binary: 10
C.filter.maskBits = 0x0001; //binary: 01
Since A and B are category 0x0001 and C has mask 0x0001, C can interact with A and B. A and B do not contain 0x0001 in their mask so cannot interact with each other.
A more in-depth explanation and example can be found here.

Structural Verilog 8-Function ALU

I know how to code an ALU using behavioral style, but I'm completely lost as to how to do it using structural design. I need an 8-function bit-slice structural ALU so I can change the word size through a parameter which gets passed and it still works. I found a schematic for a 2-function ALU, but would anyone tell me how I could translate it to 8-function or possibly link me to a Verilog example for it? Here's the 2-function ALU schematic:
I can't remember remotely enough about truth tables, k-maps, etc. to even attempt to figure out the logic for this on my own. Not sure where to even start. Any help is greatly appreciated, thanks!
Unless you are trying to simplify the logic down to a minimal form (which is honestly wasted effort as synthesis tools are very good at doing this themselves, at least when it comes to combining terms to get smaller, functional equivalent logic), you can break this problem down further. You should typically be thinking in this way when writing behavioral Verilog, as doing so makes it more likely for your design to synthesize into a workable, solid netlist.
You have a schematic, so start by taking the major pieces of the design and implementing modules to do those functions. For example, you have a number of 2x1 muxes in the design. So, we should implement logic that selects from the correct input. Now, what is a mux? Well, it s a basic combinational function that looks like this:
S A B O
----------
0 0 x 0
0 1 x 1
1 x 0 0
1 x 1 1
Ie, if S is 0, O = A, if S is 1, O = B. So, we can reformat these to logical expressions: O = ~S & A | S & B (Note, if S = 0, we will pass A and the B term will be 0'd out, and vice versa if S is 1).
Now just implement that in Verilog gate primatives:
module mux2x1(input A,
input B,
input S,
output O);
wire AO, BO, NOT_S;
not n1(NOT_S, S); // NOT_S = ~S;
and a1(AO, A, NOT_S), // AO = A & ~S;
a2(BO, B, S); // BO = B & S;
or o1(O, BO, AO); // O = (A & ~S) | (B & S);
endmodule
Now, in order to increase the width of A, B and O, we need only make a bunch of these muxes for each bit of A, B and O. We can do that but generating a much of our mux module, or but doing it to the logic inside the module like so:
module mux2x1 #(parameter W = 1)
(input [W-1:0] A,
input [W-1:0] B,
input S,
output [W-1:0] O);
wire [W-1:0] AO, BO;
wire NOT_S;
genvar i;
not n1(NOT_S, S); // NOT_S = ~S;
generate begin
for (i = 0; i < W; i = i + 1) begin : mux_w
and a1(AO[i], A[i], NOT_S), // AO[i] = A[i] & ~S;
a2(BO[i], B[i], S); // BO[i] = B[i] & S;
or o1(O[i], BO[i], AO[i]); // O[i] = (A[i] & ~S) | (B[i] & S);
end
end
endmodule
Now that you see a worked through example, I hope you can work through doing other modules the same way (like the adder and 4x1 mux). This really wasnt a formal way of doing it, but it helps to just think things through. Also note there are plenty of adder architectures online if you are having trouble figuring out the logic.

most readable programming language to simulate 10,000 chutes and ladders game plays?

I'm wondering what language would be most suitable to simulate the game Chutes and Ladders (Snakes and Ladders in some countries). I'm looking to collect basic stats, like average and standard deviation of game length (in turns), probability of winning based on turn order (who plays first, second, etc.), and anything else of interest you can think of. Specifically, I'm looking for the implementation that is most readable, maintainable, and modifiable. It also needs to be very brief.
If you're a grown-up and don't spend much time around young kids then you probably don't remember the game that well. I'll remind you:
There are 100 squares on the board.
Each player takes turn spinning a random number from 1-6 (or throwing a dice).
The player then advances that many squares.
Some squares are at the base of a ladder; landing on one of these squares means the player gets to climb the ladder, advancing the player's position to a predetermined square.
Some squares are at the top of a slide (chute or snake); landing on one of these squares means the player must slide down, moving the player's position back to a predetermined square.
Whichever player gets to position 100 first is the winner.
This is a bit rough, but it should work:
class Board
attr_accessor :winner
def initialize(players, &blk)
#chutes, #ladders = {}, {}
#players = players
#move = 0
#player_locations = Hash.new(0)
self.instance_eval(&blk)
end
def chute(location)
#chutes[location[:from]] = location[:to]
end
def ladder(location)
#ladders[location[:from]] = location[:to]
end
def spin
player = #move % #players
die = rand(6) + 1
location = (#player_locations[player] += die)
if endpoint = #chutes[location] || endpoint = #ladders[location]
#player_locations[player] = endpoint
end
if #player_locations[player] >= 100
#winner = player
end
#move += 1
end
end
num_players = 4
board = Board.new num_players, do
ladder :from => 4, :to => 14
ladder :from => 9, :to => 31
# etc.
chute :from => 16, :to => 6
# etc.
end
until board.winner
board.spin
end
puts "Player #{board.winner} is the winner!"
You should check out something along the lines of Ruby or Python. Both are basically executable psuedocode.
You might be able to get a shorter, more brilliant program with Haskell, but I would imagine Ruby or Python would probably be actually understandable.
For many statistics, you don't need to simulate. Using Markov Chains, you can reduce many problems to matrix operations on a 100x100-matrix, which only take about 1 millisecond to compute.
I'm going to disagree with some of the earlier posters, and say that an object oriented approach is the wrong thing to do here, as it makes things more complicated.
All you need is to track the position of each player, and a vector to represent the board. If the board position is empty of a chute or ladder, it is 0. If it contains a ladder, the board contains a positive number that indicates how many positions to move forward. If it contains a chute, it contains a negative number to move you back. Just track the number of turns and positions of each player.
The actual simulation with this method is quite simple, and you could do it in nearly any programming language. I would suggest R or python, but only because those are the ones I use most these days.
I don't have a copy of chutes and ladders, so I made up a small board. You'll have to put in the right board:
#!/usr/bin/python
import random, numpy
board = [0, 0, 0, 3, 0, -3, 0, 1, 0, 0]
numplayers = 2
numruns = 100
def simgame(numplayers, board):
winner = -1
winpos = len(board)
pos = [0] * numplayers
turns = 0
while max(pos) < winpos:
turns += 1
for i in range(0, numplayers):
pos[i] += random.randint(1,6)
if pos[i] < winpos:
pos[i] += board[pos[i]]
if pos[i] >= winpos and winner == -1:
winner = i
return (turns, winner)
# simulate games, then extract turns and winners
games = [simgame(numplayers, board) for x in range(numruns)]
turns = [n for (n, w) in games]
winner = [w for (t, w) in games]
pwins = [len([p for p in winner if p == i]) for i in range(numplayers)]
print "runs:", numruns
print "mean(turns):", numpy.mean(turns)
print "sd(turns):", numpy.std(turns)
for i in range(numplayers):
print "Player", (i+1), "won with proportion:", (float(pwins[i])/numruns)
F# isn't too ugly as well, its hard to beat a functional language for conciseness:
#light
open System
let snakes_and_ladders = dict [(1,30);(2,5);(20,10);(50,11)]
let roll_dice(sides) =
Random().Next(sides) + 1
let turn(starting_position) =
let new_pos = starting_position + roll_dice(6)
let found, after_snake_or_ladder = snakes_and_ladders.TryGetValue(new_pos)
if found then after_snake_or_ladder else new_pos
let mutable player_positions = [0;0]
while List.max player_positions < 100 do
player_positions <- List.map turn player_positions
if player_positions.Head > 100 then printfn "Player 1 wins" else printf "Player 2 wins"
I remember about 4 years ago being it a Top Coders competition where the question was what is the probability that player 1 win at snakes and ladders.
There was a really good write-up how to do the puzzle posted after the match. Can't find it now but this write-up is quite good
C/C++ seemed enough to solve the problem well.
Pick any object oriented language, they were invented for simulation.
Since you want it to be brief (why?), pick a dynamically typed language such as Smalltalk, Ruby or Python.