Should I use SceneManager.LoadScene("Scene Name") for infinity game? - c#

I have only 1 scene (It is infinity Game with one level)
Therefore, I can not find anywhere the differences and I would like to understand if there is performance or anything between those 2 codes:
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
SceneManager.LoadScene("Scene Name");

I would have thought
SceneManager.LoadScene(0);
would be the most efficient way because ints take up less memory than strings. Also, if you want to avoid the whole game pausing whilst the level is reloading, you could use
SceneManager.LoadSceneAsync(0);
This will load the game asyncronously in the background so the game can carry on whilst the level is reloading.

Related

How to make timer keep runing while loop wait for another time result?

i have the following issue in my code,
i have this loop running on timer (this is just a small part of the loops that running on the big timer),
inside that big timer (he tick every 1 second) i have 1 method that need to wait 5 second then continue with the the rest of the loop code, but i want that it wont stuck the code and the timer will continue to run every 1sec and wont wait for those 5sec.
what i did i add a new timer (timer_deva) that tick every 5sec and did all the checks inside it, and then timer stops.
so my issue is that i need to wait 5sec to retrieve a value to complete my code, but i need that my main timer will keep running simultaneously, and when he get his result for the other time he will need to complete the code he left behind.
thanks in advance,
else if (mobID.Equals(Convert.ToInt32(txtDeva)))
{
//START CHECK WITH TIMER
timer_deva.Start();
//Methods inside timer_deva update the winnerNation
//END CHECK TIMER - GET RESULT
winner(zoneId, winnerNation, humansKills, orcKills);
}
tl;dr
Conventional Timers are not used in games. Games have a very different mechanism for handling their logic and the time that passed.
Long Version:
I know this may not answer your question directly, but it's way to much text to cramp into a comment. Your timers sound very complicated and hierarchical. From your variable names I will assume you are programming a game. Games normally don't work with timers or not in the way you would expect. This different game-like behaviour would help you a lot in your timers problem and may even help you more with your design in general.
Games normally have something called a game loop. Generally speaking it's three main functions that are called one after the other in a loop:
while(running)
{
HandleUserInput();
ChangeWorld();
Render();
}
You get user input, you change the game world accordingly and you draw it to the screen. Now, the faster your computer is, the faster this loop runs. That's good for the graphics (think FPS), but bad for the game. Imagine Tetris where every frame the blocks move. Now I would not want to buy a faster computer, the game would get more difficult that way.
So to keep the game speed constant independent of the power of the computer, the loop considers the time passed:
while(running)
{
var timePassedSinceLastLoop = CalculateTimeDelta();
HandleUserInput();
ChangeWorld(timePassedSinceLastLoop);
Render();
}
Now imagine a cooldown for something in game. The player pressed "a", some cool action happened and although he may press "a" again, nothing will happen for the next 5 seconds. But the game still runs and does all the other things that may happen ingame. This is not a conventional timer. It's a variable, lets call it ActionCooldown, and once the player triggers the action, it's set to 5 seconds. Every time the world changes, the timePassed is subtracted from that number until it's zero. All the time, the game is running and handling input and rendering. But only once ActionCooldown hits zero, another press of "a" will trigger that action again.

MMORPG development and server side logic, update all Game Objects?

I have designed Multiplayers Games before, but now I wanted to create an MMORPG Architecture for learning/challenge purpose. I want to go as far as simulate hundreds(or a couple thousands) of concurrent players on a single server.
So far so good except that right now I am facing a problem to figure out a good way to update all game objects on the Server as often and as fast as possible.
By Game Objects I mean all Players, Mobs, Bullets.
The problem is that all Players, Mobs, Bullets are stored in a Collections on the Server Side Memory for faster processing, and iterating throught all of them to check for collisions, update health, update movement, etc... is taking way too long.
Lets say I have 1000 players and there is 10000 mobs in the whole world and all players and creatures are responsible for creating 5 other game objects(no more no less) such as bullets.
That would give (1000 + 10000) * 5 = 55000 game objects in a collection.
Iterating throught all objects, to update them, take forever(a couples minutes) on a Dual-Core HT i5 with 4gb RAM. This is wrong.
When iterating, the code look like this(pseudo):
for(int i = 0; i < gameobjects.Count; i++) {
for(int j = 0; j < gameobjects.Count; j++) {
// logic to verify if gameobjects[i] is in range of
// gameobjects[j]
}
}
As an optimization, I am thinking about dividing my game objects in different zones and collections but that wouldn't fix the problem where I need to update all objects several times per seconds.
How should i proceed to update all game objects on the server side? I did heavy search to find interesting game design patterns but no results so far. :(
Thanks in advance!
I would change the design completely and implement an event base design. This has many advantages, the obvious one is that you will only need to update the objects that are actually being interacted with. As you will always have a majority of the game objects in an MMO game being idle, or not seen at all.
There is no reason why you should calculate objects that are not visible on any players screen. That would be insane and require a server farm that you most likely cannot afford. Instead you can try to predict movement. Or store a list of all objects that are currently not interacted with and update these less frequently.
If a player can't see an object you can teleport the unit over large distances instead of having it travel smoothly. Essentially moving the unit over huge distances within the confined area that the object is allowed to move. Making it look like the object is moving freely even when the object is not visible to the players. Usually this would be triggered as an event when a new player enters, or leaves a zone.
You can achieve this by simply calculating the time since the last update and predict how far the object would have traveled, as if it was visible to the player. This is especially useful for objects or NPCs that has a set route, as it makes the calculations much simpler.
Your code is running that slow, not just because it is checking all N objects, but because it checking all possible interactions of objects, and that takes N^2 calculations = 3 025 000 000 in your sample.
One way to reduce this number of checks would be to put the object in your game world into a grid, so that objects that are not in the same or aligned cells cannot interact with each other.
Also, your current code checks each interaction twice, you can easily fix this by starting loop from i in your inner cycle:
for(int i = 0; i < gameobjects.Count; i++)
for(int j = i; j < gameobjects.Count; j++)
Looping over 55,000 objects shouldn't be too slow. Obviously, you are doing too much stuff too often over those objects and probably doing stuff that shouldn't always be done.
For example, if there is no players around a mob, should it really be calculated?
(if a tree falls in a forest and there's nobody around, does it really make a sound?)
Also, lot of objects might not need to be updated at every loop. Players for instance could be left to the client to calculate and only be "verified" once every 1-2 seconds. Dumping all the player's collision to the client would make your server workload much easier to handle. Same things for player's bullet or raycast. In return, it also makes the game much more fluid for the players.
Does mobs when following a path need to be tested for collision or can the path's nodes be enough?
Testing every objects against every other objects is terrible. Does all mobs has to be tested vs all other mobs or only specific type or faction need to be tested? Can you split your world into smaller zone that would only test mobs within it against objects also in it?
There's huge work done in MMO server's code to make it work properly. The optimizations done is sometime insane, but as long as it works.

Audio looping with XNA on Windows Phone 8 while the sound is still playing

I need a way to start/stop a loop while the sound is still playing. I've found that the best way to play multiple sounds together is to use XNA. So I've created a SoundEffectInstance starting from my SoundEffect object who contains the audio clip.
Now the problem is that I have a button which should change the state of this clip from "looped" to "non looping" and viceversa.
Here's the problem:
it throws an exception sayning that the loop must be set before the first play.
So I thought that, while switching from "non looping" to "looped", I could just wait for the sound to stop and then recreate the SoundEngineInstance, setting IsLooped = true and make it start again.
This one works, but there's some delay and this makes you lose your timing, so it's quite useless.
What I'm looking for is a way to set or unset the loop while playing the sound and without any kind of delay.
EDIT:
I tried using two SoundEngineInstance, one looped and one not, and simply switch between them using the volume.
The problem is that the non looped one just stops after the first play, so if I loop it for two times and then I put it to non loop status, no sound is played because the non looped clip already ended!
Suggestions?
I had the same proplem and I used two instances with the same audio clip to solve it, one with looping and one without it. I switched betwwen the two. It is maybe not the best solution but it worked for me.
From http://msdn.microsoft.com/en-us/library/dd940203(v=xnagamestudio.31).aspx:
Declare a SoundEffect using the method shown in How To: Play a Sound.
Declare a SoundEffectInstance, and set it to the return value of SoundEffect.CreateInstance.
Set SoundEffectInstance.IsLooped to true.
Call SoundEffectInstance.Play to play the looping sound.
You can probably set IsLooped to false when you no longer want it to loop, but only to play to the end.

How to make a function that will test if my tic tac toe AI is perfect?

Given each board state, my A.I. will return 1 exact place to move.
I also made a function that loops though all possible plays made with the A.I.
So it's a recursive function that lets the A.I. make a move for a given board, then lets the other play make all possible moves and calls the recursive function in it self with a new board for each possible move.
I do this for when the A.I goes first, and when the other one goes first... and add these together. I end up with 418 possible wins and 115 possible ties, and 0 possible loses.
But now my problem is, how do I maximize the amount of wins? I need to compare this statistic to something, but I can't figure out what to compare it to.
You can treat this as an optimisation problem with an unknown optimum solution. You can then use some form of meta-heuristic algorithm (e.g. genetic algorithm, PSO) to apply variations to your AI until you find the optimum. The interesting thing is that these algorithms might not necessarily return 'the best', but it's still useful to get something better than what you had before.
Usually meta-heuristic algorithms require a fitness function, which basically compares solutions to find the best one. In your case, you can use the win-draw ratio as a fitness function. Having already achieved a 418/115 ratio, you can use this as your 'baseline' in order to compare future solutions.
Unfortunately, I understand what I'm proposing might be too far-fetched (you might be looking for something much more simple), or it might be too general.
Unfortunately, I'm not sure about any statistic that you can use to see if it's perfect. One idea that I just quickly had is to make the assumption that:
- A perfect play only leads to a win or draw.
Your recursive algorithm already returns this. Now the question is, is it possible to increase the amount of wins? Then, you can make the assumption that:
- If both players play perfectly, the result will always be a draw (a cat's game).
Based on this assumption and together with the evaluation of the previous assumption, it means that if your AI (let's call it Bob) is perfect, in a game of Bob vs Bob, the result must always be a draw.
I realise that this still does not help you increase the number of wins (if that's possible), but it provides another metric you can use - to at least ensure that in a Bob vs Bob game, there isn't an edge case where there is a winner (which would mean your AI isn't perfect).

Controlling a remote control car with voltage drops

So my partner and I need some help; we are working on a final project which is for an electrical engineering degree. Our problem, no one really knows much programming in the class. We need help or some general ideas on how to program this.
The project:
We have a monster truck with two IR (infra red) sensors detecting it's path via voltage. with this we are using a free scale circuit board as the "brains" along with this we have a nerf "missle turret" to shoot through open doors (we need to do programming to note a voltage drop from the IR sensors.
The programming:
We are trying and struggling very, very hard to create the code for this we
need a delay function in the start of the program to set the monster truck on the ground, after we need it to follow a straight line from a set standard of voltage that the IR sensors are reading on the ground.
while it is going it will have a large V drop reading while it passes an open door, we need it to stop shoot and then follow it's path.
I know it is a lot to ask but we are in a large need for help, our teacher while wise beyond his years in everything electrical (reminds me of doc from back to the future) the c programming is lacking and not too many here have the massive knowledge to use the C programming skills.
finally, once we get this working (mid may) i will post video if able too and show you all. I appreciate any input and any ideas for this, thank you all for your time!!
Your code will probably look like:
// Give yourself some time to set the robot down
<sleep_for_some_interval>;
// Keep reading the sensors and reacting until
// some amount of time passes, or a button is pressed, etc.
while(<keep_running_condition>)
{
// Update sensor readings
int leftDist = <ConvertToDistance>(<read_left_voltage>);
int rightDist = <ConvertToDistance(<read_right_voltage>);
// React to sensor readings
if(leftDist > <door_threshold> &&
rightDist > <door_threshold>)
{
// A door has been detected.
<stop>
<shoot>
<move_forward_fixed_amount>
}
else if(leftDist > <turn_threshold>)
{
// Left distance is beyond the threshold,
// need to turn left
<turnLeft>;
}
else if(rightDist > <turn_threshold>)
{
// Right distance is beyond the threshold,
// need to turn right
<turnRight>
}
else (<terminate_condition>)
{
// Something happened (a sensor condition, etc)
// that tells us that we need to end
// the program
break; // This will exit the while loop
}
else (...)
{
// Other conditions...
}
else
{
// Default reaction (happens if none of the previous
// conditions are met)
<goForward>
}
}
// Shutdown the robot
<stop>
// ...
Obviously the comparisons may need to be different, but the basic idea will be to continually read your sensors, and then have a list of conditions to check and actions to take when conditions are met.
Notes/Hints:
To "delay ... in the start of the program" you will call something like sleep/usleep
Make sure that you check your conditions in the right order (check the most restrictive conditions first) In the above example, if I moved the "turnLeft" check to the top, I might end up turning left instead of reacting to the door.
The way the above code is written, only one reaction will happen on each pass through the loop. (This will prevent you from accidentally trying to do two things when you should only be doing one, e.g. turning left and firing)
It may be helpful to write a function that can convert a voltage to a distance
Your code will be cleaner and easier to maintain if you take complicated actions (like the reaction after you detect a door) and move them into their own function.
Make sure to use some form of revision control, even if you do nothing more than periodically zip up your development directory. It will be very helpful when you find that you've introduced a bug into your code.
Out of curiosity, is there a reason you can't do all this in hardware? I'm assuming a lot about your project, but I'd think at least #1 might even be easier to do in hardware if that's your area of expertise. Unless, of course, you have instructions to do this in software that you must obey.
If the IR sensors are already outputting variable voltage, couldn't you just scale the voltage output from the sensors to drive the motors? I'm assuming the wheels are driven by motors and you're spinning one faster than the other to get it to turn. Then you might even get a smoother driving pattern (turning/adjusting as you go), as opposed to the standard software solution, which is go-or-turn.
For #2, you could implement a state machine. This could take care of the delay as well, just throw a timer between state 0 (waiting) and state 1 (normal). Then use the voltage output from the door sensor to trigger state 2 (firing). If you need, you can split it into two states, 2 (arming) and 3 (firing), with another timer between the two. The wheel motors are only active in state 1, and release the missile trigger when state 3 occurs.
Most universities have a programming club (i know mine did) - why not hang around there, see if anyone wants to help?
Or even put something on the noticeboard around the computer rooms at uni, i'm sure most good programmers would find it a fun project to lend a bit of time to.
Being that it is a physical project you've got there, you really want someone there 'on the ground' with you, so to speak.

Categories