I've looked around Stack Overflow for a solution but have not found one to a problem I have with random NPC movement. Essentially, what I have coded up to now, is a simple 2D platformer game using Sprite Kit: there's a separate class for the NPC object. I initialize it in my GameScene (SKScene) no problem & so far it's behaving with the physicsWorld I have set up properly. Now I'm at the part where it simply needs to move randomly in any direction. I've set up the boundaries & have made it move with things like SKActions, utilizing things like CGPointMake, that would move the NPC randomly as needed, have it wait a little bit in that location & resume movement. BOOL's helped this process. However, I had difficulty getting the sprite to look left when moving left & looking right when moving right (looking up & down is not needed at all). So I found a way in a book by using Vector's. I set up a method in the NPC class which is used in the GameScene:
-(void)moveToward:(CGPoint)targetPosition
{
CGPoint targetVector = CGPointNormalize(CGPointSubtract(targetPosition, self.position));
targetVector = CGPointMultiplyScalar(targetVector, 150); //150 is interpreted as a speed: the larger the # the faster the NPC moves.
self.physicsBody.velocity = CGVectorMake(targetVector.x, targetVector.y); //Velocity vector measured in meters per second.
/*SPRITE DIRECTION*/
[self faceCurrentDirection]; //Every time NPC begins to move, it will face the appropriate direction due to this method.
}
Now all of this works. But the issue at hand is calling this moveToward method appropriately in the update method. The 1st thing I tried was this:
-(void)update:(NSTimeInterval)currentTime
{
/*Called before each frame is rendered*/
if (!npcMoving)
{
SKAction *moving = [SKAction runBlock:^{ npcMoving = YES }]; //THIS IS THE CULPRIT!
SKAction *generate = [SKAction runBlock:^{ [self generateRandomDestination]; }]; //Creates a random CGFloat X & CGFloat Y.
SKAction *moveTowards = [SKAction runBlock:^{ _newLocation = CGPointMake(fX, fY);
[_npc moveToward:_newLocation]; }]; //Moves NPC to that random location.
SKAction *wait = [SKAction waitForDuration:4.0 withRange:2.0]; //NPC will wait a little...
[_npc runAction:[SKAction sequence:#[moving, generate, moveTowards, wait]] completion:^{ npcMoving = NO; }]; //...then repeat process.
}
}
The vector method 'moveToward' requires 'update' method to be present for NPC movement to happen. I turn this off with 'npcMoving = YES' in the beginning in hopes that the NPC will move to targeted location & start the process again. This is not the case. If I remove SKAction with 'npcMoving = YES', the 'update' method calls upon the entire sequence of above SKActions every frame, which in turn doesn't move my NPC far. It simply has it change targeted location every frame, in turn creating an 'ADHD' NPC. Could someone please recommend what to do? I absolutely need to retain the vector movement for the directional properties & other future things but I am at a loss on how to properly implement this with the 'update' method.
Actions perform a task over time. If your npcMoving flag is false, you run an action sequence every frame, which means over 10 frames you will have 10 action sequences running simultaneously. That will cause undefined behavior.
Next, even if you were to stop the existing sequence and run it anew, running an action every frame where at least one action has a duration is practically pointless. Because then that action with duration will not be able to complete its task in the given time because it'll be replaced the next frame.
Summary: actions with duration are unsuitable for tasks that require adjustment every frame.
Solutions:
perform tasks by changing the actor's properties (ie position etc) as/when needed (ie every frame)
decide on a task for the actor, then run the corresponding action sequence for that task and wait for it to end before you decide upon a new task
Related
I am suddenly in a recursive language class (sml) and recursion is not yet physically sensible for me. I'm thinking about the way a floor of square tiles is sometimes a model or metaphor for integer multiplication, or Cuisenaire Rods are a model or analogue for addition and subtraction. Does anyone have any such models you could share?
Imagine you're a real life magician, and can make a copy of yourself. You create your double a step closer to the goal and give him (or her) the same orders as you were given.
Your double does the same to his copy. He's a magician too, you see.
When the final copy finds itself created at the goal, it has nowhere more to go, so it reports back to its creator. Which does the same.
Eventually, you get your answer back – without having moved an inch – and can now create the final result from it, easily. You get to pretend not knowing about all those doubles doing the actual hard work for you. "Hmm," you're saying to yourself, "what if I were one step closer to the goal and already knew the result? Wouldn't it be easy to find the final answer then ?" (*)
Of course, if you were a double, you'd have to report your findings to your creator.
More here.
(also, I think I saw this "doubles" creation chain event here, though I'm not entirely sure).
(*) and that is the essence of the recursion method of problem solving.
How do I know my procedure is right? If my simple little combination step produces a valid solution, under assumption it produced the correct solution for the smaller case, all I need is to make sure it works for the smallest case – the base case – and then by induction the validity is proven!
Another possibility is divide-and-conquer, where we split our problem in two halves, so will get to the base case much much faster. As long as the combination step is simple (and preserves validity of solution of course), it works. In our magician metaphor, I get to create two copies of myself, and combine their two answers into one when they are finished. Each of them creates two copies of themselves as well, so this creates a branching tree of magicians, instead of a simple line as before.
A good example is the Sierpinski triangle which is a figure that is built from three quarter-sized Sierpinski triangles simply, by stacking them up at their corners.
Each of the three component triangles is built according to the same recipe.
Although it doesn't have the base case, and so the recursion is unbounded (bottomless; infinite), any finite representation of S.T. will presumably draw just a dot in place of the S.T. which is too small (serving as the base case, stopping the recursion).
There's a nice picture of it in the linked Wikipedia article.
Recursively drawing an S.T. without the size limit will never draw anything on screen! For mathematicians recursion may be great, engineers though should be more cautious about it. :)
Switching to corecursion ⁄ iteration (see the linked answer for that), we would first draw the outlines, and the interiors after that; so even without the size limit the picture would appear pretty quickly. The program would then be busy without any noticeable effect, but that's better than the empty screen.
I came across this piece from Edsger W. Dijkstra; he tells how his child grabbed recursions:
A few years later a five-year old son would show me how smoothly the idea of recursion comes to the unspoilt mind. Walking with me in the middle of town he suddenly remarked to me, Daddy, not every boat has a lifeboat, has it? I said How come? Well, the lifeboat could have a smaller lifeboat, but then that would be without one.
I love this question and couldn't resist to add an answer...
Recursion is the russian doll of programming. The first example that come to my mind is closer to an example of mutual recursion :
Mutual recursion everyday example
Mutual recursion is a particular case of recursion (but sometimes it's easier to understand from a particular case than from a generic one) when we have two function A and B defined like A calls B and B calls A. You can experiment this very easily using a webcam (it also works with 2 mirrors):
display the webcam output on your screen with VLC, or any software that can do it.
Point your webcam to the screen.
The screen will progressively display an infinite "vortex" of screen.
What happens ?
The webcam (A) capture the screen (B)
The screen display the image captured by the webcam (the screen itself).
The webcam capture the screen with a screen displayed on it.
The screen display that image (now there are two screens displayed)
And so on.
You finally end up with such an image (yes, my webcam is total crap):
"Simple" recursion is more or less the same except that there is only one actor (function) that calls itself (A calls A)
"Simple" Recursion
That's more or less the same answer as #WillNess but with a little code and some interactivity (using the js snippets of SO)
Let's say you are a very motivated gold-miner looking for gold, with a very tiny mine, so tiny that you can only look for gold vertically. And so you dig, and you check for gold. If you find some, you don't have to dig anymore, just take the gold and go. But if you don't, that means you have to dig deeper. So there are only two things that can stop you:
Finding some gold nugget.
The Earth's boiling kernel of melted iron.
So if you want to write this programmatically -using recursion-, that could be something like this :
// This function only generates a probability of 1/10
function checkForGold() {
let rnd = Math.round(Math.random() * 10);
return rnd === 1;
}
function digUntilYouFind() {
if (checkForGold()) {
return 1; // he found something, no need to dig deeper
}
// gold not found, digging deeper
return digUntilYouFind();
}
let gold = digUntilYouFind();
console.log(`${gold} nugget found`);
Or with a little more interactivity :
// This function only generates a probability of 1/10
function checkForGold() {
console.log("checking...");
let rnd = Math.round(Math.random() * 10);
return rnd === 1;
}
function digUntilYouFind() {
if (checkForGold()) {
console.log("OMG, I found something !")
return 1;
}
try {
console.log("digging...");
return digUntilYouFind();
} finally {
console.log("climbing back...");
}
}
let gold = digUntilYouFind();
console.log(`${gold} nugget found`);
If we don't find some gold, the digUntilYouFind function calls itself. When the miner "climbs back" from his mine it's actually the deepest child call to the function returning the gold nugget through all its parents (the call stack) until the value can be assigned to the gold variable.
Here the probability is high enough to avoid the miner to dig to the earth kernel. The earth kernel is to the miner what the stack size is to a program. When the miner comes to the kernel he dies in terrible pain, when the program exceed the stack size (causes a stack overflow), it crashes.
There are optimization that can be made by the compiler/interpreter to allow infinite level of recursion like tail-call optimization.
Take fractals as being recursive: the same pattern get applied each time, yet each figure differs from another.
As natural phenomena with fractal features, Wikipedia presents:
Moutain ranges
Frost crystals
DNA
and, even, proteins.
This is odd, and not quite a physical example except insofar as dance-movement is physical. It occurred to me the other morning. I call it "Written in Latin, solved in Hebrew." Huh? Surely you are saying "Huh?"
By it I mean that encoding a recursion is usually done left-to-right, in the Latin alphabet style: "Def fac(n) = n*(fac(n-1))." The movement style is "outermost case to base case."
But (please check me on this) at least in this simple case, it seems the easiest way to evaluate it is right-to-left, in the Hebrew alphabet style: Start from the base case and move outward to the outermost case:
(fac(0) = 1)
(fac(1) = 1)*(fac(0) = 1)
(fac(2))*(fac(1) = 1)*(fac(0) = 1)
(fac(n)*(fac(n-1)*...*(fac(2))*(fac(1) = 1)*(fac(0) = 1)
(* Easier order to calculate <<<<<<<<<<< is leftwards,
base outwards to outermost case;
more difficult order to calculate >>>>>> is rightwards,
outermost case to base *)
Then you do not have to suspend items on the left while awaiting the results of calculations further right. "Dance Leftwards" instead of "Dance rightwards"?
When an object collides with a wall, it cannot pass through but some of the sprite can. When the wall is on the right, the collision works fine but when approaching from another way, part of the object collides.
I have different collision code for different objects, so it's probably not the problem. The reason for this is that different objects react differently to the collision and they also move differently.
The event for my character that is controlled by the user
hor = keyboard_check(ord("D"))-keyboard_check(ord("A"));
ver = keyboard_check(ord("S"))-keyboard_check(ord("W"));
if (place_meeting(x+(hor * sp),y,Object_Wall))
{
while (!place_meeting(x+sign(hor * sp),y,Object_Wall))
{
x += sign(hor);
}
hor = 0
}
if (place_meeting(x,y+(ver * sp),Object_Wall))
{
while (!place_meeting(x,y+sign(ver * sp),Object_Wall))
{
y += sign(ver);
}
ver = 0
}
x += hor * sp;
y += ver * sp;
The code for the enemy which randomly roams around and should walk away after hitting the wall (Collision with wall event)
move_towards_point(random(room_width),random(room_height),sp)
time = random_range(50,150)
The problem with the enemy only occurs while he is chasing the player, so now that I think about it, the characters collision is probably the problem.
Any help on how to fix it?
You probably have a bug when checking the condition of collision, but it is hard to pinpoint your exact problem without seeing the definition of your sprite and your code (post them, please, but make them a Minimal, Complete, and Verifiable Example first).
Regarding your sentence: "I have different collision code for different objects, so it's probably not the problem." - well, this is a problem indeed. Why to have different code for the same task? You are asking for troubles... And that may well be the reason you see the problem now (e.g. the actual collision-checking code in action is not the one you think it is...).
I'm currently learning Elm. relatively new to functional programming. i'm trying to understand this example from http://elm-lang.org/learn/Using-Signals.elm on counting mouse-clicks. they provide the following code:
clickCount =
foldp (\click count -> count + 1) 0 Mouse.clicks
They explain that foldp takes three arguments: a counter-incrementer, which we defined as an anonymous function with two inputs, a starting state 0, and the Mouse.clicks signal.
I do not understanding why we need the variable click in our anonymous function. Why can't we just have \count -> count + 1? Is the extra input getting bound to one of our inputs into foldp?
thanks!
You need it because foldp expects a function with two inputs. In this case, the first input is just ignored by your lambda, but the foldp implementation still puts something in there. Mouse.clicks always puts a sort of do-nothing value called Unit in there.
Some signals have a value associated with them, like Mouse.position, for example. If you wanted to do something like measure how far the mouse has moved, you would need to use that parameter.
I've read some of the discussions here, as well as followed links to other explanations, but I'm still not able to understand the mathematical connection between "changing state" and "not changing state" as it pertains to our functional programming versus non-FP debate. As I understand, the basic argument goes back to the pure math definition of a function, whereby a function maps a domain member to only one range member. This is then compared to when a computer code function is given certain input, it will always produce the same output, i.e., not vary from use to use, i.e.i.e., the function's state, as in its domain to range mapping behavior, will not change.
Then it get foggy in my mind. Here's an example. Let's say I want to display closed block-like polygons on an x-y field. In GIS software I understand everything is stored as directed, closed graphs, i.e. a square is four vectors, their heads and ends connected. The raw data representation is just the individual Cartesian start and end points of each vector. And of course, there might be a function in the software that "processed" all these coordinate sets. Good. But what about representing each polygon in a mathematical way, e.g., a rectangle in the positive x, negative y quadrant might be:
Z = {(x,y) | 3 <= x <= 5, -2 <= y <= -1}
So we'd have many Z-like functions, each one expressing an individual polygon -- and not being a whiz with my matrix math, maybe these "functions" could then be represented as matrices . . . but I digress.
So with the usual raw vector-data method, I've got one function in my code that "changes state" as it processes each set of coordinates and then draws each polygon (and then deals with polygons changing), while the one-and-only-one-Z-like-function-per-polygon method would seem to hold to the "don't change state" rule exactly. Right? Or am I way off here? It seems like the old-fashioned, one-function-processing-raw-coordinate-data is not mutating the domain-range purity law either. I'm confused....
Part of my inspiration came from reading about a new idea of image processing where instead of slamming racks of pixels, each "frame" would be represented by one big function capable of "gnu-plotting" the whole image, edges, colors, gradients, etc. Is this germane? I guess I'm trying to fathom why I would want to represent, say, a street map of polygons (e.g. city blocks) one way or the other. I keep hearing functional language advocates dance around the idea that a mathematical function is pure and safe and good and ultimately Utopian, while the non-FP software function is some sort of sloppy kludge holding us back from Borg-like bliss.
But even more confusing is memory management vis-a-vis FP versus non-FP. What I keep hearing (e.g. parallel programming) is that FP isn't changing a "memory state" as much as, say, a C/C++ program does. Is this like the Google File System where literally everything is just sitting out there in a virtual memory pool, rather than being data moved in and out of databases and memory locations? Somehow all these things are related. Therefore, it seems like the perfect FP program is just one single function (possibly made up of many sub-functions) doing one single task -- although a quick glance at any elisp code seems to be a study of programming schizophrenia on this count.
Referential transparency in programming (and mathematics, logic, etc.) is the principle that the meaning or value of an expression can be determined without needing any non-local context, and that the value of an expression doesn't change. Code like
int x = 0;
int nextX() {
return x++;
}
violates referential transparency in that nextX() will at one moment return 32, and at the next invocation return 33, and there is no way, based only on local analysis, what nextX() will return in any given location. It is easy in many cases to turn a non-referentially transparent procedure into a referentially transparent function by adding an argument to the procedure. For instance, in the example just given, the addition of a parameter currentX, makes nextX referentially transparent:
int nextX( int currentX ) {
return currentX+1;
}
This does require, of course, that every time nextX is called, the previous value is available.
For procedures whose entire purpose is to modify state (e.g., the state of the screen), this doesn't make as much sense. For instance, while we could write a method print which is referentially transparent in one sense:
int print( int x ) {
printf( "%d", x );
return x;
}
there's still a sort of problem in that the state of the system is modified. Methods that ask about the state of the screen will have different results before and after a call to print, for instance. To make these kinds of procedures referentially transparent, they can be augmented with an argument representing the state of the system. For instance:
// print x to screen, and return the new screen that results
Screen print( int x, Screen screen ) {
...
}
// return the contents of screen
ScreenContents returnContentsOfScreen( Screen screen ) {
...
}
Now we have referential transparency, though at the expense of having to pass Screen objects around. For instance:
Screen screen0 = getInitialScreen();
Screen screen1 = print( 2, screen0 );
Screen screen2 = print( 3, screen1 );
...
This probably feels like overkill for working with IO, since the intent is, after all, to modify some state (namely, the screen, or filesystem, or …). Most programming languages, as a result, don't make IO methods referentially transparent. Some, like Haskell, however, do. Since doing it as just shown is rather cumbersome, these language will typically have some syntax to make things a bit more clean. In Haskell, this is accomplished by Monads and do notation (which is really out of scope for this answer). If you're interested in how the Monad concept is used to achieve this, you might be interested in this article, You Could Have Invented Monads! (And Maybe You Already Have.)
I'm very interested in Kick.js. To convince my professor to use this framework, I want to develop an application which I can load/code custom 3D model using kick.js and should be able to add more objects. I should also able to print FPS to check the variations in FPS as I add more 3D objects on canvas. I'm new to graphic programming, I neither have knowledge on shader programming nor openGL. Being a newbie, how can I start diving into this framework?
The following steps I wanted to implement (Suggest me if I go wrong):
Develop simple demo using kick.js loading single cube or sphere or teapot on canvas.
Able to see the fps as I change the camera angles.
Later I should be able to add more triangles(Models) on the canvas of same type (ex: Teapot) and able to compare the fps with single teapot one.
Am i approaching the right way or please suggestions needed. The provided tutorials neither of them having FPS demo. Please someone HELP ME. I really liked the features stated on homepage but I don't know how can I implement them in my demo.
Assuming that Kick.js has a "render" callback or something similar that's invoked for each frame you want to render (and you know the time between frames, or the absolute time since program start), it's fairly simple to calculate your frame rate.
The method I've used before is: pick a sample rate (I like 250ms so it updates 4 times a second), and count how many frames have executed every 250ms. When you hit 250ms, update the on-screen frame rate counter variable and start counting again.
timeSinceLastFPSUpdate += millisecondsSinceLastFrame;
framesSinceLastFPSUpdate++;
if timeSinceLastFPSUpdate > 250:
timeSinceLastFPSUpdate = 0
fps = framesSinceLastFPSUpdate * (1000 / 250); // convert "frames per 250ms" to "frames per 1s"
framesSinceLastFPSUpdate = 0;
print fps to screen;
You can play around with different sample rates or use a different frame rate calculation method to get the timer to be more "accurate" (to better find frame rate dips) but it sounds like you're looking for something that's less accurate and is just giving you a reasonable idea of the overall complexity of rendering rather than frame to frame dips.