How to set fps in pygame in order to prevent lag? - python-2.7

How can I set a suitable fps number in pygame for any kind of monitor running my game? I know I can set fps using pygame.time.Clock().tick(fps) but how can I set suitable fps?
Please post example python code along with answer.

I'm not entirely sure that I understand the question being asked, but I think you will just have to experiment with different numbers and find out what works for you. I find that around 50-100 is a good range.
If what you are trying to do is make game events only update a certain number of times per second while rendering happens as fast as the computer is able to handle it, this is a very complex process and probably not very easily done in pygame.

The trick I've figured out is not limiting the frame rate, but calculating based on time. The pygame.time.Clock.tick() returns time in milliseconds, which you can then pass to other parts of the program to calculate events or animation updates.
For example, I currently use a pair of variable in my Player object to store the center point of the player's character multiplied by 1000 to be able to update it as an int from tick(). I think update it each loop, after solving which direction the player is moving, with the following code:
self.x += self.speed * time * xmove
self.y += self.speed * time * ymove
self.rect.centerx = self.x / 1000
self.rect.centery = self.y / 1000
Additionally, I use that same time variable as part of the Spawner class to determine when new enemies should be spawned to the map, and for the movement of the enemies and bullets in the game.
This method has the bonus of keeping game play more or less the same across multiple frame rates.

Related

opencv - prediction collision of ball

I want to do a project, which will consist in detecting possible collision of the pool balls, using opencv, webcam and C++ programming language. For now I just want to prediction collision of 2 balls on minibilard table. I detect them by change rgb to hsv and then use thereshold, in future i will probably use another method for detect a random amount of balls, but it's not so important now.
So, for now I can detect two balls, i know their position, radius, now I'm thinking how to predict whether there will be a collision between them, if we if we assume that they will move in straight lines. I think that I should check their position in every frame update (and i have to know a time between frames in my webcamera) and by that, i I will be able to determine the value of speed, acceleration and direction of the ball. So, if i will know those parameters for for both balls, I will be able to determine where can they collide, and then, using parametric equastion I will be able to check, if they will be on collision point on the same time.
I wonder if this is the right approach to the problem, maybe there is a simpler and more effective method to do this?
Thanks for any kind of help.
Karol
This sounds like you are on track for a good project...
Calculating acceleration seems, from what I briefly read here, reasonably difficult though. So as a preliminary step, you could just assume a constant velocity. So take the difference between a balls position last frame and current frame as a vector and add it on to the current frames position to find where it will be next frame. Doing this for both balls will allow you to check for a collision.
You can check for a collision by comparing the distance between the balls centers using Pythagoras to the sum of their radii. If the sum of their radii will be greater than the distances between their centers, you have a collision.
Obviously, calculating one frame ahead is not very useful, but if you assume a constant velocity or manage to calculate their acceleration, there is no reason to why you can't calculate 30 or 100 frames in the future with this method.
I recently made a billiards ball simulation in javascript which you could take a quick look at here if you want to see how this could work.

Disjoint Movement of Joints of Aldebaran Nao

I am working on a locomotion system for the Aldebaran Nao. I noticed that my robot's motions are very disjoint as compared to those on other robots - a problem that I am pretty sure is code related.
I am updating my robots motions using code similar to Aldebaran's fast get set DCM.
(http://doc.aldebaran.com/1-14/dev/cpp/examples/sensors/fastgetsetdcm/fastgetsetexample.html).
I am updating the joint angles every 10 ms (the fastest possible update rate). However, it is clear that the motors move to the newly commanded angle very quickly and are motionless for the majority of the 10 ms. Is there any way to control the velocity of the motors during this 10ms update period?
There's many way to send order to joints using DCM or ALMotion.
The easiest way is using ALMotion, with that you can use
angleInterpolationWithSpeed, where you'll specify a ratio of speed.
angleInterpolation, where you'll specify a time. In this example 0.01 sec.
Using the DCM, you just have to ask for the movement to finish 10ms later.
The ALMotion and DCM documentation are well wrotten, you should have a look...

Physics [UE4]: Implement a "maximum compression" for vehicle-suspension

For a given vehicle, I implemented a suspension system on four wheels.
The system is based on Hooke's Law.
The Problem: The vehicle should not be able to touch the ground. When driving in a spherical container (inside), the suspension gets compressed up to 100%, making the vehicle chassis touch the underground, which leads to unwanted collisions that throw the vehicle around.
Despite that may being a realistical behaviour, our game aims for an arcade-feeling, so I am looking for a formula to implement a maximum compression, so that the vehicle chassis can't come closer to the underground than X percent of the suspension size at any given moment, without actually simulating a physical contact between the two rigid bodys. Thus, I need to apply a fake force to the suspensions.
My current approach:
If the vehicle chassis would in fact touch the suspension base (Sorry, I don't know the proper word to describe this. I mean, when the suspension is at maximum compression), a force equal in magnitude and opposite in direction relative to the force pushing onto the suspension would be applied to the vehicle chassis, forcing it to stop moving downwards.
Therefore, I receive my vehicles world velocity V.
To get the downwards-velocity, I get the DotProduct of the velocity and the BodyUpVector.
float DownForceMagnitude = DotProduct(VelocityAtSuspension, BodyUpVector);
FVector DownForce = DownForceMagnitude * BodyUpVector;
FVector CounterForce = -DownForce * WeightOnSuspension;
Okay, this pseudo-code works somewhat fine on even underground, when the vehicle lands on a plane after a jump. Driving on a increasing slope however (like driving on the inside-walls of a sphere), makes the suspension reach maximum compression anyway, so apparently my approach is not correct.
I am now wondering what the cause is. My weight calculation only is simulated by VehicleWeight / 4, since the Unreal Engine 4 has no functionality to receive weight at a given location. I am no physics-pro, so forgive me if this is easy to calculate. Could that be the issue?
I do not need a physically 100% plausible solution, I just need a solution that works, and sufficiently stops the downwards motion of my vehicle chassis.
Any help is appreciated.
Greetings,
I had this problem with a futuristic magnetic hovercraft.
I solved it by reducing the force by ln depending on suspensions extension levels like so:
y = ln(ln(x+e))
where:
x = Suspension extension lvl in % (-> 0 being fully compressed)
y = the factor that you multiply the force with
e = eulers number
Here a graphic to help what it will be like:
https://ggbm.at/gmGEsAzE
ln is a very slow growing function thats why it works so great for this.
You probably want to clamp the values (maybe between 0 and 100 idk exactly how your code behaves and how u want this "break" to behave)
Tailor the function to your needs, I just wanted to suggest u use the ln like I did to solve this Problem.
I added e to x first to make it go through 0,0 if u want to make it stop earlier just subtract from x before using ln.
Also notice depending on when/how you calculate / update your suspension this (and any function applied to the force based on the extension of suspension levels) may not work under some circumstances or at all.

C++ 3D perfect collision detection

I'm having hard time learning collision detection by experience. I'm making a box game, à la Minecraft, and am at the stage of implementing collision detection.
I've done x and y axis', since everything consists of cubes I would like to make my own collision detector and make it as light as possible.
Is there a way to make "pixel perfect" collisions, that is when the player's bounding box (or circle) touches a box it registers as a collision? Right now this is what I did:
if(-TOUCH_DISTANCE-1 < yPlayer-yBox && yPlayer-yBox < TOUCH_DISTANCE-1)
{
collisionNorth = true;
}
if(-TOUCH_DISTANCE+1 < yPlayer-yBox && yPlayer-yBox < TOUCH_DISTANCE+1)
{
collisionSouth = true;
}
It basically detects the collision within a certain margin and that means errors, which I don't like :(. Notice the +/-1 which offsets the "collision wall" to the respective side of the box.
This works, on lower speeds, but once there's some action (when I crack up the speed variable) the collision can't be detected anymore since I go too fast and pass right through the cube... Is there a way to make it wallhax0r proof?
This is especially annoying on z axis, when the player falls at high speed and even when defining a respectable collision margin it will ultimately look nasty (player half buried).
You've identified one of the problems of using discrete mathematics to model the path of an object. At time t the object is "here" and at time t + delta it's "there" - without actually having passed through the points in between.
You can get more accuracy by decreasing delta, but ultimately you are going to hit the limit of what you can calculate in that time interval.
If you can detect a collision approaching by using a relatively large time delta and loose bounding box you could then crank up the accuracy, but again you are going to hit limits.
Converting to a continuous model might help - but may take more computational power. You could switch to this when your objects are close so you're not doing it all the time.
Sorry I've not got a definite answer, only pointers.
Usually what you need to do is keep track of the previous position of the objects as well as the current position. Then when you update, you can check if the objects intersected during the time period, rather than if they intersect 'at the moment'.

Cocos2D Asteroids

For school I have to make a game for my iPod touch, I chose to do an asteroids game. I have just started with cocos2d but have read the wenderlich blog. I wanted to use chipmunk in my game, i want realisitc motion of the ship. Is there a tutorial on creating the asteroids motion?
Thanks.
Simple Way
Learn a bit about vectors. http://chortle.ccsu.edu/VectorLessons/vectorIndex.html
Movement is usually calculated by adding a vector scaled by a time delta to the current position. (Math talk makes simple things so complicated).
Basically: new_Pos = old_Pos + mov_Vec * time_delta
So by changing the mov_Vec you can increase/decrease speed.
You can also do it on x,y new_x = old_x + mov_x * time_delta
Using Physics Library
If you are using a physics library, you can apply force to an object to move it. You can also set the angular velocity if you want it to rotate.
If you were using Box2d you would do something like this:
body->ApplyImpulse( b2Vec2(1,1), body->GetWorldCenter() );
There's a difference between applying force and an impulse in box2d
Some sites to check out
http://gpwiki.org/
http://www.gamedev.net/
http://www.devmaster.net/
http://box2d.org/
Airship motion in space is pretty easy to simulate... I don't think you need a library for that.
The ship has a velocity vector: depending on your input method, you shall only add a vector to change the speed (or reduce modulo when braking, if braking is allowed).
Just limit the max modulo of the ship, and you're done.
Sorry if this isn't really a reply to your answer.
HIH