I was just wondering if there was a way to change the amount of time until the sleep state is activated for a body in box2d (cocos2d).
I currently use the sleep state as a way to end a game so it is preferable if I can speed up the time it takes to achieve the sleep state.
Thanks
A physics engine doesn't put objects to sleep based on time. It only puts bodies to sleep which are at rest (idle). Typically the physics engine defines rules when it's safe to put a body to sleep, normally that's when the body has stopped moving at all, when there are no other moving bodies touching it, and when both conditions are met for a certain period of time.
In Box2D you can't modify this behavior unless you modify the Box2D source code (not recommended). In Chipmunk you can at least set the threshold for how long a body must be idle before it is put to sleep. Changing this value can sometimes lead to the effect that slow moving objects will suddenly fall to sleep.
To implement the behavior you want, you should define your own set of rules. Iterate over all bodies that may be moving slowly at the end of the game. Get the values for angular rotation and velocity, and check if they have fallen below a certain threshold that feels good for your game. Then end the game, or you can also manually put the object to sleep with body->SetAwake(false).
Related
I'm trying to build a 2D, orthogonal game that generates the map randomly. Many of tiles in the map are gatherable resources that the player character can interact with. In order to achieve this, a Agents/Components approach is used, giving these entities a physics body (with isDynamic set to false to avoid unnecessary calculations) in order to detect collisions (i.e. when the player reaches a resource and attempts to gather it). SpriteKit seems to quickly be unable to handle anything bigger a small 150x150 map memorywise, on the actual target device.
Is this approach fundamentally flawed? Is Unity a better choice in this case?
This can be a solution:
Create a pool for physics body of each type, like pool for trees physics bodies, stones and etc.
It will be empty for a moment, for each element in the array at the beginning of a game check for close objects to the player, iterating through 60k array will be faster, then background calculation of all physics moments and holding 60k physics bodies in memory. To check for the close objects there is no need for you to count correct distance(doing pow(x, 2) + pow(y, 2) is not an easy operation), it will be enough for you to mark object as close if abs(player.x - obj.x) < 100 && abs(player.y - obj.y) < 100 is true. This operation costs less, and it is still better.
2.1 If true. Then you take a physics body from the pool and assign it to this node or create a new physics body of pool is empty.
2.2 If false. Then you save physics body of this node to the pool and remove it from the node
Its not a perfect solution, I'm not sure if it will give you a lot of profit, but it will decrease a number of physics body on a scene paying for such move with an iterating through a big array(that shall not take a lot of time), and making a basic operations like + and abs.
It's in your choice, when you should such checks, this can be by a Timer, or in update, or every time, you player moves on some constant distance(like every 100points), it can be an experimental part.
I'm a senior software engineer, but completely new to Unity programming. I've been teaching myself Unity for a few weeks by writing some SteamVR toys for myself. I wanted to ask about Unity's standard built-in ways to improve frame rate for a program with a lot of intensive physics calculation.
In my current VR scene, I have a ball with a Rigidbody on it. When I pick it up and throw it, I let it move naturally, but I apply small forces on every Update() call to adjust the landing position and always hit a target.
I saw my framerate take a big dive, so I wrote my own function to throttle the updates, limiting them to 5 per second. The question is, is there some standard Unity behavior that I should be using instead of rolling this code myself?
In my throwing script, I maintain a bunch of top level variables and update them first to decide whether I should do calculations on the current frame.
private void updateCalculationFrame() {
isCalculationFrame = Time.time > nextCalculationTime;
while (nextCalculationTime < Time.time) {
nextCalculationTime += (1 / calculationsPerSecond);
}
}
On each frame, I run this function, then if isCalculationFrame is true, I proceed to calculate and add force vectors. I just wonder if I am overlooking some more standard way to do this with less code? I feel like this must be a very common thing to try to do.
The code you have there will freeze the Unity until the loop is finished. You shouldn't do this at all.
You could simply set a new Time.fixedDeltaTime. By default it is usually about 0.02 but you can set it to anything you want.
The interval in seconds at which physics and other fixed frame rate updates (like MonoBehaviour's FixedUpdate) are performed.
...
Note that the fixedDeltaTime interval is with respect to the in-game time affected by timeScale.
I have a particle effect for a muzzle flare set up. What I'm currently using is a low numParticlesToEmit to limit the emitter to a short burst, and doing resetSimulation() on the emitter whenever I want to start a new burst of particles.
The problem I'm having is that resetSimulation() removes all particles onscreen, and I often need to create a new burst of particles before the previous particles disappear normally so they get erased early.
Is there a clean way start up the emitter again without erasing the particles already onscreen?
Normally particle systems have a feature missing from SKEmitters: a duration. This controls how long a system emits. I don't see this in SKEmitter, despite being in SCNParticleSystems
Never mind, a work around:
SKEmitters have a numParticlesToEmit property and a particleBirthRate. Combined, these determine how long the particle system emits before shutting down.
Using these as a control of the emission it's possible to create pulses of particles emitted in the way you want for something like a muzzle flash or explosion.
I'm not sure if it remvoes itself when it reaches this limit. If not, you'll have to create a removal function of some sort. Because the way to get your desired effect (multiple muzzle flashes on screen) is to copy() the SKEmitter. This is quite efficient, so don't worry about overhead.
There is a targetNode on SKEmitters that are suppose to move the particles to another node so that when you reset the emitter, the previous particles still stay. Unfortunately, this is still bugged from what I can tell, unless somebody else has figured out how to get it working and I just missed it. Keep this in mind though in case they do ever fix it.
Hi to help future readers, the code that I use to calculate the duration of the emitter is this:
let duration = Double(emitter.numParticlesToEmit) / Double(emitter.particleBirthRate) + Double(emitter.particleLifetime + emitter.particleLifetimeRange/2)
It works perfectly for me
Extension:
extension SKEmitterNode {
var emitterDuration: Double {
return Double(numParticlesToEmit) / Double(particleBirthRate) + Double(particleLifetime + particleLifetimeRange/2)
}
}
I am currently developing an AI system in Unity3D and am wondering if anyone could suggest which of the following awareness models are better?
Use Physics.OverlapSphere at a constant rate of about every 2 seconds to check a range for anything of interest.
Use a Sphere Trigger Collider that is attached to the AI, when an object enters this trigger it starts getting monitored.
Mostly worried about performance vs quality, I have a feeling that model 1 is faster until the AI needs to check everything around it for a particular item, in which case model 2 would return quicker as it already has the collection of local interests. However, will model 2 take up more resources as a trigger collider needs to be sending out checks every physics update?
Your 2nd approach is best way to do it, even though,i can easily say that it all depends on your requirements and both have their own uses. (I am "only absolute way of doing things kinda guy")
With Trigger
void OnTriggerEnter(Collider other)
you can only get one collision body out of many that have collided. It is faster if you have large collisions and u can definetly expand and contract the radius of your trigger to almost use it as the same effect as overlapping sphere (but not recommended for guaranteed results). As it detects only one collided body its not processor intensive.
With Overlap sphere approach you can
Collider[] OverlapSphere(Vector3 position, float radius, int layerMask, QueryTriggerInteraction queryTriggerInteraction);
you can get collider[] or multiple collision bodies that have collided. This is processor intensive, if you have 50 objects colliding and performance will drop the time you call upon this function.
Another Approach.
For simplicity and proper design of mechanics, Trigger bodies can solve for any complicated scenario. I must advice you, from my experience it is always the perspective you rely upon to solve your problem is the factor that will limit your thoughts and ultimately your results.
Keeping that in mind, I would like you try this approach...create a method that uses
public static float Distance(Vector3 a, Vector3 b);
to give you a boolean answer to detect your actor. It is a very good approach since only a language primitive is streamed (between 2 actors) and not an object and performance of in-built function is just negligible. You can have each enemy actor register themselves (their reference) in the List (to get all actors of interest) inside main actor actor if they are at desired proximity (so yes your enemy checks whether its close than the main actor and tells the actor that he is the one who is very close).
I have tested this approach with 20 other actors having their own scripts running in ipod gen 5, with almost no performance drop.
I have a game where I use a lot of SKActions to deliver the desired game logic.
For example, instead of setting the zRotation of a sprite to a value, I would use runAction(SKAction.rotateTo(/* angle here */, duration: 0.0) instead.
I make calls like this in update, and in touchesMoved. Thus this could mean hundreds of these calls, sometimes nested with groups of other actions.
Am I incurring significant overhead relative to directly setting the zRotation property?
Never use SKActions for real-time motion. Instead you should either set the zRotation directly or set the necessary angular velocity each frame. In your case the update method and touchesMoved method are both bad to use for SKActions because they can run 30-60 times a second.
SKActions do generate significant overhead. Here is a quote from Apple's documentation:
When You Shouldn’t Use Actions
Although actions are efficient, there
is a cost to creating and executing them. If you are making changes to
a node’s properties in every frame of animation and those changes need
to be recomputed in each frame, you are better off making the changes
to the node directly and not using actions to do so. For more
information on where you might do this in your game, see Advanced
Scene Processing.
Source
You can see an example of using real-time motion instead of SKActions in my answer here
You should not call a SKAction in the update method as it is called 60 times a second. Instead, use a event based trigger which in turn calls the SKAction. The touchesMoved is a good example of that. You can also use a completion method block to signal for a new SKAction upon completion of the current action.