How to calcuate velocity of 2D object using mouse moments without a game engine? - 2d

Just like the title suggests, I want to know how I would go about doing this. For example:
In this case, I can get the average speed for the mouse per frame and that would be the velocity. Pretty straightforward, right? Well, it gets complicated when you consider that the person might pick up the object, not move the mouse position for 1/2 of the time and then move it at 100 px/s but the average speed would only end up being 50 px/s which looks wrong.
I don't actually need the code for doing this, I just need to know how to do it.
Comment if you need more information and thank you!

Related

Collision Detection pygame

im currently making a small game by following youtube tutorials. i followed this tutorial by Clear code for the movement: https://www.youtube.com/watch?v=4aZe84vvE20&t=230s&ab_channel=ClearCode
i wanted to take my game to the next level and add a few blocks around the map which the user has to avoid. i want to make it so that if the car hits a block it stops and only moves when the user rotates it to face away from the block, into an empty space. right now, in the player class, ive created a collision attribute and have used pygame.sprite.spritecollide(self, blocks, True) to check for collision. the blocks variable is a group containing all the sprites for the blocks.
if there is a collision, i change the vector to (0,0), which stops the car, like intended. however, i cant figure out a way to change the vector again once ive rotated the car so that it faces away from the block, to get it going again. any help is appreciated. thanks in advance.
Do not change the motion vector to (0, 0). As soon as a collision is detected, change the position of the car so that the car only touches the object but does not intersect the object.
Something like (pseudo code):
if collide_at_left_side:
car.rect.left = obstacle.rect.right
A more general solution would be to correct the position along the normal vector of the collision.

How to prevent RangeError: Maximum call stack size exceeded in a finite recoursive function? | JavaScript

I am trying to make a Connect 4 Bot which uses a minimax algorithm to function.
Apparantly going through all the possible game states is too much for my program, so I need a way to prevent the error from happening.
I saw that you could use setTimeout() to make big recursive functions runnable in JavaScript but I didn't really find a way to understand it.
So I wanted to ask if anybody could maybe make an example of how to implement setTimeout() into an recoursive function to make it runnable.
(Sorry for possible english mistakes.)
I would say a better way is to use the so called iterative deepening. I don't know Javascript at all, so forgive me for posting in pseduocode/Python.
start_time = current_time
for depth in range(1, inf):
score = minimax(depth, ......)
if current_time - start_time >= max_allowed_time:
break
So you get the time when you start the loop. Then you go deeper and deeper (from depth 1 and onwards) until the current time minus the time you started looping is more than your specified maximum time value. Now it will search for as deep as it can within the given time limit.
At first glance this might seem to be slower than just searching for a given depth. But it will actually speed up your code if you implement for example move ordering and transposition tables later on. And since the time for each depth goes up exponentially, the time it takes to search first depth 1, then 2, then 3 is negligible larger than searching for just depth 3 right away.
Hope I make myself clear, Englihs is not my native language either :)

How to achieve realistic reflection with threejs

I am trying to render as realistically as possible a scene in which a point light hits an object and bounces off with the same angle wrt the normal of the face (angle of incidence = angle of reflection) and illuminates the scene elsewhere.
Now, I know reflection in threejs is normally dealt with CubeCamera-material as per the examples I found online, but it doesn't quite apply to my case, for I may be observing the scene from a point in which I might not be able to observe the reflection of the object on the mirror-like surface of another one.
Consider this example prototype I'm working on: if the box that is protruding from the wall in the scene had a mirror-like material (accomplished with a CubeCamera), I wouldn't be able to see the green cube's reflection on the bottom face unless the camera was at a specific position; in real life, however, if an object illuminated by a light source passes in the vicinity of another one, it will in part light it as if it were a light source itself (depending on the object's index of reflectivity, of course) and such phenomenon should be visible from any point of view the object receiving indirect lighting is visible from.
Hence I came up with the idea of adding a PointLight to the cube, but this of course produces undesirable effects on the surroundings.
I will try to illustrate my goal with the following sequence:
1) Here, the far side of what I will henceforth refer to as balcony is correctly dark, while the areas marked with a red 'x' are the consequence of the cube having a child PointLight which shines in all directions.
2) Here, the balcony's far face is still dark and the bottom one is receiving even more light as the cube passes by, which is desirable, but the wall behind the cube should actually be dark (I haven't added shadows yet, I first want to get the lighting right), as well as the ground beneath it and the lamp post.
3) Finally, when the cube has passed the balcony, it's just plain wrong for the balcony's side and bottom face to be illuminated, for we all now that a reflected ray does not bounce back the way it came from. Same applies to the lamp post.
Now I realize that all the mistakes that occur are due to the fact that the cube emits light itself, what I'm hoping you can help me with is determining a way to produce physically accurate reflected rays.
I would like to avoid using ambient light or other hacks to simulate real-life scenarios and stick to physics as much as possible; I suspect what I want to achieve is very computationally heavy to render, let alone animate in a real-time use case, but that's not an issue for I'm merely trying to develop a proof-of-concept, not something that should necessarily perform fast.
From what I gather, I should probably be writing custom vertex and fragment shaders for the materials receiving indirect illumination, right? Unfortunately I wouldn't know where to begin, can anyone point me in the right direction? Cheers.
If you do not want to go to the Volumetric rendering then you have 3 options (I know of)
ray-tracing
you have to use ray-trace rendering (back ray-trace) to achieve this. This will also cover shadows,transparent materials,reflected illumination and much more if coded properly. Unless you want to do also precise atmospheric scattering then this is the way.
back raytracing is one (or 3) ray(s) per each screen pixel. It is much faster but not that precise.. (still precise enough)
raytracing is one ray per each 3D angular unit (steradian) of space per each light source. It is slow but precise (if ray density is high enough).
If the casted ray hits any obstacle then its color is changed (due to obstacle property) and new ray is casted as reflected light ray. If material is transparent then also refracted ray is casted ... Each hit or refraction affect light intensity so you stop when intensity is lower then some treshold or on some layer of recursion (limit max number of refractions per ray) to avoid infinite loops and you can manipulate performance/quality ...
standard polygon rendering
With this approach (I think you are using it right now) you have to improvise. The reflection and illumination effects can be done similar to shadowing techniques. For each surface you have to render the scene in reflected direction. The same can be done with shadows but then you just rendering to the light direction or use shadow map instead. If you have insane number of reflective surfaces then this approach is not the way also to achieve reflection of refraction you have to render recursively making it multiple rendering pass per polygon which is also insane.
cubemap
You can use cube map per each object. It is similar to bullet 2 but the insanity is done just once while generating cubemaps instead of per frame ... If you have too much objects then this is also not the way. You can use cube map only for objects with reflective surfaces to make it manageable. Also if the objects are moving then you have to re-generate cubemaps once in a while ...

Complex movement within animation

I've this application, where two children are playing catch. One throws and the other catches. While I can show a ball object moving between two stationary objects, how do I show the objects "releasing" and "catching" the ball, in a way that is close to lifelike?
EDIT:
The movement of the hands in this game: http://www.acreativedesktop.com/animation-game-slaphands.html is what I would like to replicate. Any tips on how to do that?
As it's already been stated, you need animation to get it right. I suggest looking over Preston Blair's Cartoon Animation Book or The Animator's Survival Kit. You won't need to read the whole thing, just reference the chapters on anticipation and accents.
For example, when one throws, the action doesn't just happen, one first prepares, anticipating the throw, building up energy. In animation you prepare the viewer for the next action, thus creating a seamless link between actions. Once the ball is thrown...there is action and re-action, so the player will return to his casual pose.
The actionscript part should be pretty simple. You should get away with 3 vectors:
1 for setting the balls movement
1 for gravity
1 for friction/wind...etc.
Based on your parameters, you launch the ball, then use the distance between the ball and the catcher to figure out when you can you play the catcher's animation(s)
skeletal animation is a good technique
also reverse kinematics
or even motion-capture
I know this is essentially possible in flash... it does however sound pretty complex. My advice would be to create static animations for the throw action and the catch action, then have these actions play when certain conditions are met (i.e. the ball gets close to one of the people). Trying to get a lifelike throw and catch will be pretty tough. I would think even a lot of console games wouldn't attempt to do this dynamically (i do expect this is in the process or is changing in current gen games)

How many game updates per second? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
What update rate should I run my fixed-rate game logic at?
I've used 60 updates per second in the past, but that's hard because it's not an even number of updates per second (16.666666). My current games uses 100, but that seems like overkill for most things.
None of the above. For the smoothest gameplay possible, your game should be time-based, not frame-locked. Frame-locking works for simple games where you can tweak the logic and lock down the framerate. It doesn't do so well with modern 3D titles where the framerate jumps all over the board and the screen may not be VSynced.
All you need to do is figure out how fast an object should be going (i.e. virtual units per second), compute the amount of time since the last frame, scale the number of virtual units to match the amount of time that has passed, then add those values to your object's position. Voila! Time-based movement.
I used to maintain a Quake3 mod and this was a constant source of user-questions.
Q3 uses 20 'ticks per second' by default - the graphics subsystem interpolates so you get smooth motion on the screen. I initially thought this was way low, but it turns out to be fine, and there really aren't many games at all with faster action than q3
I'd personally go with the "good enough for john carmack, good enough for me"
I like 50 for fixed rate pc games. I can't really tell the difference between 50 and 60 (and if you are making a game that can/cares you should probably be at 100).
you'll notice the question is 'fixed-rate game logic' and not 'draw loop'. For clarity, the code will look something like:
while(1)
{
while(CurrentTime() < lastUpdate + TICK_LENGTH)
{
UpdateGame();
lastUpdate += TICK_LENGTH;
}
Draw();
}
The question is what should TICK_LENGTH be?
Bear in mind that unless your code is measured down to the cycle, not each game loop will take the same number of milliseconds to complete - so 16.6666 being irrational is not an issue really as you will need to time and compensate anyway. Besides it's not 16.6666 updates per second, but the average number of milliseconds your game loop should be targeting.
Such variables are generally best found via the guess and check strategy.
Implement your game logic in such a way that is refresh agnostic (Say for instance, exposing the ms/update as a variable, and using it in any calculations), then play around with the refresh until it works, and then keep it there.
As a short term solution, if you want an even update rate but don't care about the evenness of the updates per second, 15ms is close to 60 updates/sec. While if you are about both, your closest options is 20ms or 50 updates/sec is probably the closest you are going to get.
In either case, I would simply treat time as a double (Or a long with high-resolution), and provide the rate to your game as a variable, rather then hard coding them.
The ideal is to run at the same refresh-rate as the monitor. That way your visuals and the game updates don't go in and out of phase with each other. The fact that each frame doesn't last an integral number of milliseconds shouldn't matter to you; why is that a problem?
I usually use 30 or 33. It's often enough for the user to feel the flow and rare enough not to hog the CPU too much.
Normally I don't limit the FPS of the game, instead I change all my logic to take the time elapsed from last frame as input.
As far as fixed-rate goes, unless you need a high rate for any reason, you should use something like 25/30. That should be enough rate, and will be making your game a little lighter on CPU usage.
Your engine should both "tick" (update) and draw at 60fps with vertical sync (vsync). This refresh rate is enough to provide:
low input lag for a feeling of responsiveness,
and smooth motion even when the player and scene are moving rapidly.
Both the game physics and the renderer should be able to drop frames if they need to, but optimize your game to run as close to this 60hz standard as possible. Also, some subsystems like AI can tick closer to 10-20fps, and make sure your physics are interpolated on a frame-to-frame time delta, like this: http://gafferongames.com/game-physics/fix-your-timestep/

Resources