How to create a floor with Chipmunk library - ruby

I'm using Ruby and, of course, the Ruby bindings to Chipmunk as well as the Chingu/Gosu game libraries. Seems like the syntax is different but otherwise I assume it's the same as Chipmunk C. How do I make a floor? I tried the following:
space = CP::Space.new
space.damping = 0.9
space.gravity = CP::Vec2.new(0, 50)
body = CP::StaticBody.new
shape_array = [CP::Vec2.new(0, 400), CP::Vec2.new($window.width, 400), CP::Vec2.new($window.width, 390), CP::Vec2.new(0, 390)]
shape = CP::Shape::Poly.new(body, shape_array, CP::Vec2.new(0,0))
shape.collision_type = :floor
space.add_body(body)
space.add_shape(shape)
What happens is objects hit the floor and kind of wiggle for a split second, then pass right through. I want them to land on the floor, maybe even bounce up a little (depending on the object). But not go through the floor. How do I do this?

To make this work, I had to remove the line:
space.add_body(body)
Static bodies can't be added to space.

Related

Moving GameObject without transform.position through a touchscreen? (In Unity3d)

I'm developing a mobile game in Unity3d which the player needs to move a stick that is placed just a little bit higher then the finger with transform.position and block a ball that is moved with Force.Mode2D.impulse. The problem is that the ball goes through the stick if the stick is moved too fast. Could anyone please teach me how to code the stick movement with Force (or any other way that works) that still moves according to the finger position on touch screen ( A.K.A Input.mousePosition) instead of using buttons?
The code goes as such if anyone needs the info;
Stick:
float defencePosX = Mathf.Clamp( Input.mousePosition.x / Screen.width * 5.6f - 2.8f , -2.8f, 2.8f);
float defencePosY = Mathf.Clamp( Input.mousePosition.y / Screen.height * 10 - 4f, -3.3f, -0.5f);
this.transform.position = new Vector3 (defencePosX, defencePosY, 0);
Ball:
projectileSpeed = Random.Range (maxSpeed, minSpeed);
projectileSwing = Random.Range (-0.001f, 0.001f);
rb.AddForce (new Vector2 (projectileSwing * 1000, 0), ForceMode2D.Impulse);
rb.AddForce (new Vector2 (0, projectileSpeed), ForceMode2D.Impulse);
a video of the bug:
https://youtu.be/cr2LVBlP2O0
basicly if i dont move the stick it hits but if i move it fast the ball goes right through. (the bouncing sound effect doesnt work if itss too fast as well)
When working with physics objects, you'll want to use just the Rigidbody component when moving them. Otherwise, it's interpreted as a teleport and no physics is applied and no movement is calculated.
Try using Rigidbody.MovePosition instead of transform.position.
Also, make sure the Rigidbody components on your stick AND ball both have collisionDetectionMode set to 'Continuous Dynamic'. That's how you get small fast-moving physics objects to hit one another in between frames.
float defencePosX = Mathf.Clamp( Input.mousePosition.x / Screen.width * 5.6f - 2.8f , -2.8f, 2.8f);
float defencePosY = Mathf.Clamp( Input.mousePosition.y / Screen.height * 10 - 4f, -3.3f, -0.5f);
rb.MovePosition(new Vector3 (defencePosX, defencePosY, 0));
Id recommend that you set the balls force to Vector3.zero before adding force to it, or that you use the collider of your blocking movement as a bounce pad for the ball.
Please remember to check that your colliders are scaled correctly according to the blocker.
A video displaying your issue would be helpful to understand it better.

Physijs stops updating?

I'm trying to make a small project using Three.js & the physics plugin physijs; just a little dice roller. My approach is to use setGravity to move the dice around, modelling gravity to move the dice around. The issue I'm running into is that once the dice come to a rest, they no longer respond to gravity. Has anyone run into this before?
Whats happening:
Ammo.js, on which Physijs is based, puts resting or very slow moving objects in a sleep state to save performance. So when you change the worlds gravity the sleeping objects dont care, because Physijs doesnt tell them gravity has changed.
You have the ability to modify the sleeping thresholds, set activation states or just quickly activate the rigid bodys before changing gravity.
Please note this code applys to native Ammo.js, I am not sure how to
do this when using physijs but you get the idea.
Solution 1: Loop over your Bodys and activate them, then change gravity:
// dice is an array with your rigid bodys
for ( var i = 0; i < dice.length; i ++ ) {
// hey wake up
dice[ i ].activate();
}
physicsWorld.setGravity( new Ammo.btVector3( 0, -9.81, 0 ) );
Solution 2: Thou shall get no sleep, do this after creating your dice:
var DISABLE_DEACTIVATION = 4;
for ( var i = 0; i < dice.length; i ++ )
// no sleep for you... ever
dice[ i ].setActivationState( DISABLE_DEACTIVATION );
}

Performance problems with scenekit

I've got a row dimensional array of values that I want to visualize in 3D and I'm using scene kit under OS X for it. I've done it in a clumsy manner by using each column as a point on the X axis, each row as a point on the Z axis, and each value as a normalized point on the Y axis -- I place a sphere at the vector defined by each data point. It works but it doesn't look too good.
I've also done this by building a mesh of lines based on #Matthew's function in Drawing a line between two points using SceneKit (the answer he posted, not the original question). For each point I use his function to draw two lines - one between my current point and the next point to the right and another between my current point and the next point towards the front (except when there is no additional column/row, of course).
Using the second method, my results look much better... however the performance is quite hideous! It takes quite a long time to complete the initial rendering, and if I use a trackpad/mouse to rotate or translate the scene, I might as well get a cup of coffee to wait until my system is usable again (and this is not much hyperbole). Using the sphere method, things render and update very quickly.
Any advice on how to improve the performance when using the lines method? (Note that I am not trying to add both lines and spheres at the same time.) Code-wise, the only difference between approach is which of the following methods gets called (and that for each point, addPixelAt... is called once, but addLineAt... is called twice for most points).
- (SCNNode *)addPixelAtRow:(CGFloat)row Column:(CGFloat)column size:(CGFloat)size color:(NSColor *)color
{
CGFloat radius = 0.5;
SCNSphere *ball = [SCNSphere sphereWithRadius:radius*1.5];
SCNMaterial *material = [SCNMaterial material];
[[material diffuse] setContents:color];
[[material specular] setContents:color];
[ball setMaterials:#[material]];
SCNNode *ballNode = [SCNNode nodeWithGeometry:ball];
[ballNode setPosition:SCNVector3Make(column, size, row)];
[_baseNode addChildNode:ballNode];
return ballNode;
}
- (SCNNode *)addLineFromRow:(CGFloat)row1 Column:(CGFloat)column1 size:(CGFloat)size1
toRow2:(CGFloat)row2 Column2:(CGFloat)column2 size2:(CGFloat)size2 color:(NSColor *)color
{
SCNVector3 positions[] = {
SCNVector3Make(column1, size1, row1),
SCNVector3Make(column2, size2, row2)
};
int indices[] = {0, 1};
SCNGeometrySource *vertexSource = [SCNGeometrySource geometrySourceWithVertices:positions count:2];
NSData *indexData = [NSData dataWithBytes:indices length:sizeof(indices)];
SCNGeometryElement *element = [SCNGeometryElement geometryElementWithData:indexData
primitiveType:SCNGeometryPrimitiveTypeLine
primitiveCount:1
bytesPerIndex:sizeof(int)];
SCNGeometry *line = [SCNGeometry geometryWithSources:#[vertexSource] elements:#[element]];
SCNMaterial *material = [SCNMaterial material];
[[material diffuse] setContents:color];
[[material specular] setContents:color];
[line setMaterials:#[material]];
SCNNode *lineNode = [SCNNode nodeWithGeometry:line];
[_baseNode addChildNode:lineNode];
return lineNode;
}
From the data that you've shown in your question I would say that your main problem is the number of draw calls. Your's is in the tens of thousands, which is way too much. It should probably be a lot closer to ~100.
The reason why you have so many draw calls is that you have so many distinct objects in your scene (each line). The better (but more advanced solution) would probably be to generate a single element for the entire mesh that consists of all the lines. If you want to achieve the same rendering with that mesh (with a color from cold to warm based on the height) then you could do that in a shader modifier.
However, in your case I would start by flattening all the lines (since that would be the smallest code change and should still have a significant performance improvement in your case).
(Optimizing performance is always an iterative process. Once you fix one thing there will be another thing which is the most expensive operation. Without your code I can only say what would help with the current performance problem)
Create an empty node (without adding it to your scene) and generate all the lines, adding them to this node. Then create a flattened copy of that node by calling flattenedClone on the node that contains all the lines
SCNNode *nodeWithAllTheLines = [SCNNode node];
// create all the lines and add them to it...
SCNNode *flattenedNode = [nodeWithAllTheLines flattenedClone];
[_baseNode addChildNode:flattenedNode];
When you do this you should see a significant drop in the number of draw calls (the number after the diamond in the statistics) and hopefully a big increase in performance.

Creating THREE.Line's with different endpoints using THREE.BufferGeometry

I am creating several THREE.Lines using THREE.BufferGeometry. Initially my app had them all starting at the origin and things worked as expected. Now, I would like to be able to start (and end) them at any point.
This fiddle (http://jsfiddle.net/9nVqU/) illustrates (I hope) how changing one end of the line away from the origin causes unexpected results.
I wondered if it was because any given line follows on from the previous one - switching the start/end order didn't change anything though so if that were true, I'd expect it to break.
Maybe I have the arrays set up incorrectly or the attributes that tell THREE.js how to interpret it - I think I need 2 * 3 verts for each line but changes I made to buffer_geometry.attributes = { seemed to make things worse.
FWIW, the actual effect I'm trying to achieve is to selectively turn on and off the lines based on user input. I can do that already by changing the end position but then I lose that value and I don't want to store it elsewhere. I thought that I could move the start point to the end point to switch it off and then move the start point to the origin again to re-enable it. If there is a way to enable/disable lines individually with BufferGeometry, then that would clearly be better.
First of all, you would have to do this:
var line = new THREE.Line( buffer_geometry, material );
line.type = THREE.LinePieces;
Second, this is not supported in r.58 , but should be.
As a work-around, you can hack WebGLRenderer.renderBufferDirect() like so:
// render lines
setLineWidth( material.linewidth );
var position = geometryAttributes[ "position" ];
primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
_gl.drawArrays( primitives, 0, position.numItems / 3 );
_this.info.render.calls ++;
_this.info.render.points += position.numItems;
three.js r.58

XNA: Identifying identical sprites created with for loop

G'day all,
In short, I'm using a for loop to create a bunch of identical sprites that I want to bounce around the screen. The problem is how do I write a collision detection process for the sprites. I have used the process of placing rectangles around sprites and using the .intersects method for rectangles but in that case I created each sprite separately and could identify each one uniquely. Now I have a bunch of sprites but no apparent way to pick one from another.
In detail, if I create an object called Bouncer.cs and give it the movement instructions in it's update() method then create a bunch of sprites using this in Game.cs:
for (int i = 1; i < 5; ++i)
{
Vector2 position = new Vector2(i * 50, i * 50);
Vector2 direction = new Vector2(i * 10, i * 10);
Vector2 velocity = new Vector2(10);
Components.Add(new Bouncer(this, position, direction, velocity, i));
}
base.Initialize();
I can draw a rectangle around each one using:
foreach (Bouncer component1 in Components)
{
Bouncer thing = (Bouncer)component1;
Rectangle thingRectangle;
thingRectangle = new Rectangle((int)thing.position.X, (int)thing.position.Y, thing.sprite.Width, thing.sprite.Height);
But now, how do I check for a collision? I can hardly use:
if (thingRectangle.Intersects(thingRectangle))
I should point out I'm a teacher by trade and play with coding to keep my brain from turning to mush. Recently I have been working with Python and with Python I could just put all the sprites into a list:
sprites[];
Then I could simply refer to each as sprite[1] or sprite[2] or whatever its index in the list is. Does XNA have something like this?
Please let me know if any more code needs to be posted.
Thanks,
Andrew.
One solution, which I use in my game engine, is to have a Logic code run inside the objects for every game Update, ie. every frame. It seems you already do this, according to the variable names, which indicate you run some physics code in the objects to update their positions.
You might also want to create the collision rectangle inside the Bouncer's constructor so it's more accessible and you make good use of object oriented programming, maybe even make it an accessor, so you can make it update every time you call it instead of manually updating the bounding/collision box. For example:
public Rectangle #BoundingBox {
get { return new Rectangle(_Position.X, _Position.Y, width, height); }
}
Whichever way works, but the collision checks can be run inside the Bouncer object. You can either make the reference list of the Bouncer objects static or pass it to the objects itself. The code for collisions is very simply:
foreach(Bouncer bouncer in Components) //Components can be a static List or you can pass it on in the constructor of the Bouncer object
{
if (bouncer.BoundingBox.Intersects(this.BoundingBox))
{
//they collided
}
}

Resources