XNA Accelerate Object every 10 seconds - windows-phone-7

I am trying to figure out a way to make an object increase in speed every 10 seconds. The increase is nominal, something like 0.1. I am working with gameTime.Secondsand gameTime.TotalSeconds to figure out a solution but haven't nailed one yet.
My game is based on WP7/WP8
Does anyone know how I can do this?
EDIT:
I've just tried this:
if (gameTime.TotalSeconds % 30 == 0)
{
Speed += SpeedAcceleration;
}
But it falls in the if ALL the time.

something like this should work
int timeSnapshot = 0;
if(gameTime.ElapsedGameTime.TotalSeconds - timeSnapshot >= 10){
Speed += SpeedAcceleration;
timeSnapshot = gameTime.ElapsedGameTime.TotalSeconds;}

Related

Minus from slider value in AfterEffects

I'm making a timer. When the minutes value reaches 60, it has to decrease by 60 and increment the hour. It's tracking a time lapse; the minutes is currently the time of the computation divided by 6 : each frame is 10 seconds in real life.
This is the code I have so far:
effect("Mins")(1)+Math.floor(((time*10)/6))+effect("MinAdd")("Slider");
if(effect("Mins")("Slider").value > 60) {effect("Mins")("Slider") -60;}
Unfortunately, it doesn't work, and I don't know why.
I'm not quite sure what your setup is there, but usually property values are read by reading the .value property and set through setValue(), so in your case e.g.
effect("Mins")("Slider").setValue(effect("Mins")("Slider").value - 60);
Personally I'd probably use something more along the lines of:
var currentsec = (time*10)/6);
var minute = Math.floor(currentsec / 60);
var sec = currentsec % 60;
effect("Mins")("Slider").setValue(minute);
effect("Seconds")("Slider").setValue(sec);
though in your case of course for minutes and hours.

Collision not detecting at high speed

I decided I wanted to learn how to work with the unity2D engine, and started with trying to make pong. This was going pretty good, until I found a problem I couldn't find/didn't understand an answer for on google .
Every time the player/AI hits the ball, I make the ball go a little bit faster. This works fine until the ball goes pretty fast (still playable though) and just passes through the player/AI. I solved this by making the box collider of the player/AI really long, but at really high (and unplayable) speeds it still goes through.
My solution works, but isn't that pretty, and I wonder if there is a better solution for this (make the engine check more often for collisions?).
Here's the script for the ball movement (Javascript):
#pragma strict
var StartSpeed : int;
var speedFactor : float;
function Start () {
yield WaitForSeconds(2);
StartBall();
}
function ResetBall () {
GetComponent.<Rigidbody2D>().velocity.x = 0;
GetComponent.<Rigidbody2D>().velocity.y = 0;
transform.position.x = 0;
transform.position.y = 0;
yield WaitForSeconds(0.5);
StartBall();
}
function StartBall () {
var randomDirection = Random.Range(0f,1f);
var randomAngle = Random.Range(-Mathf.PI/4, Mathf.PI/4);
if(randomDirection < 0.5f){
GetComponent.<Rigidbody2D>().velocity.x = Mathf.Cos(randomAngle) * StartSpeed;
GetComponent.<Rigidbody2D>().velocity.y = Mathf.Sin(randomAngle) * StartSpeed;
}else{
GetComponent.<Rigidbody2D>().velocity.x = - Mathf.Cos(randomAngle) * StartSpeed;
GetComponent.<Rigidbody2D>().velocity.y = Mathf.Sin(randomAngle) * StartSpeed;
}
}
function OnCollisionEnter2D (colInfo : Collision2D) {
if(colInfo.collider.tag == "Player"){
GetComponent.<Rigidbody2D>().velocity.x = speedFactor * GetComponent.<Rigidbody2D>().velocity.x;
if(colInfo.collider.GetComponent.<Rigidbody2D>().velocity.y == 0){
GetComponent.<Rigidbody2D>().velocity.y = speedFactor * GetComponent.<Rigidbody2D>().velocity.y;
}
var vel = GetComponent.<Rigidbody2D>().velocity;
Debug.Log("Speed: " + vel);
}
}
Any other comments on the script that may improve it are welcome!
EDIT: I tried the following (as Andrew suggested):
function OnCollisionEnter2D (colInfo : Collision2D) {
if(colInfo.collider.tag == "Player"){
GetComponent.<Rigidbody2D>().AddForce( Vector2 (speedFactor * GetComponent.<Rigidbody2D>().velocity.x, speedFactor * GetComponent.<Rigidbody2D>().velocity.y));
var vel = GetComponent.<Rigidbody2D>().velocity;
Debug.Log("Speed: " + vel);
}
}
This still causes the problem I had before.
Update your RigidBody settings and set Collision Detection to Continuous (it will probably be set to discrete) and your high speed collision will work fine.
You shouldn't be messing with the velocity directly, try just using AddForce() instead.
Whole physics including collision detection runs on FixedUpdate, so to actually detect any collision colliders must collide when FixedUpdate is called. Let's say one collider isn't moving (wall for example) and another is going right at it, on current call of FixedUpdate collider that is moving is just before the wall, while on the next call of FixedUpdate collider that is moving has passed the wall, because that is it's position step per frame. Visually we see that colliders did collide, but they didn't collide on any call to FixedUpdate. Now, there are two solutions to this, lower the speed or lower the timestep of FixedUpdate ( http://docs.unity3d.com/Manual/class-TimeManager.html ), but this can be bad for framerate, it all depends what machines are you targeting and how hardware hungry your game is.
There is also this open source script which you should look at :
http://wiki.unity3d.com/index.php?title=DontGoThroughThings#C.23_-_DontGoThroughThings.js

1-2-3 star level awards algorithm

What I am trying to do is to have individual star counts per level based on player performance. (1-2-3 star awards.) This will be based on what region the player reaches. I know how to award the stars but keeping track of it all is throwing me problems. First lets say a player plays level 2 and receives 1 star for their performance. Then at a later time, s/he returns to the level and gets a 2 star. I would like the star count for that specific scene to update to two stars, while only adding 1 star ( The one extra s/he got this time) to the totalStarCount.
My initial plan was to have variables:
OldStarCount
NewStarCount
TotalStarCount
Then when a player reaches say region1, and is awarded one star, then NewStarCount would be set to one, then
TotalStarCount = TotalStarCount + (NewStarCount - OldStarCount);
Then update OldStarCount = NewStarCount;
Set NewStarCount = 0;
Move On to next Scene;
Am I approaching this the correct way? Any help would be greatly appreciated.
You could have something like this
int result = 0;
int totalStars = 0;
int[] starCounts = new int[NumberOfRegions};
...
currentRegion = 42;
result = play(currentRegion);
if(result > starCounts[currentRegion]){
totalStars += result - starCounts[currentRegion];
starCounts[currentRegion] = result;
}
This is just an example of what you could do. There are obvious scalability issues with this (what happens when you want to add new regions, etc), but you get the gist.

How to end a game after an interval of time(in XNA)

I have created a game using XNA Game Studio. It consists of a square randomly moving anywhere and on clicking it, the score increases by one.
Now, what I want to do is, I want to end it after a time interval of, say, 100 seconds. So how do I do it? And where should I write that part of the code? That is, in which method? I am very new to XNA. Its just two days since I have started learning it.
In your update loop check the elapsed game time greater than 100 seconds:
int counter = 0;
protected override void Update(GameTime gameTime)
{
counter += gameTime.ElapsedGameTime.TotalSeconds;
if ( counter > 100 )
{
//end the game...
}
}
If you want the total game time since the game started, you can use the TotalGameTime property instead, then you won't need the counter.

Write code to make CPU usage display a sine wave

Write code in your favorite language
and let Windows Task Manager represent
a sine wave in CPU Usage History.
This is a technical interview quiz from Microsoft China.
I think it's a good question. Especially it's worth knowing how candidate understand and figure out the solution.
Edit: It's a good point if may involve multi-core(cpu) cases.
A thread time slice in Windows is 40ms, iirc, so that might be a good number to use as the 100% mark.
unsigned const TIME_SLICE = 40;
float const PI = 3.14159265358979323846f;
while(true)
{
for(unsigned x=0; x!=360; ++x)
{
float t = sin(static_cast<float>(x)/180*PI)*0.5f + 0.5f;
DWORD busy_time = static_cast<DWORD>(t*TIME_SLICE);
DWORD wait_start = GetTickCount();
while(GetTickCount() - wait_start < busy_time)
{
}
Sleep(TIME_SLICE - busy_time);
}
}
This would give a period of about 14 seconds. Obviously this assumes there is no other significant cpu usage in the system, and that you are only running it on a single CPU. Neither of these is really that common in reality.
Here's a slightly modified #flodin's solution in Python:
#!/usr/bin/env python
import itertools, math, time, sys
time_period = float(sys.argv[1]) if len(sys.argv) > 1 else 30 # seconds
time_slice = float(sys.argv[2]) if len(sys.argv) > 2 else 0.04 # seconds
N = int(time_period / time_slice)
for i in itertools.cycle(range(N)):
busy_time = time_slice / 2 * (math.sin(2*math.pi*i/N) + 1)
t = time.perf_counter() + busy_time
while t > time.perf_counter():
pass
time.sleep(time_slice - busy_time);
A CPU-curve can be fine-tuned using time_period and time_slice parameters.
Ok I have a different, probably BETTER solution than my first answer.
Instead of trying to manipulate the CPU, instead hook into the task manager app, force it to draw what you want it to instead of CPU results. Take over the GDI object that plots the graph, etc. Sort of "Cheating" but they didnt say you had to manipulate the CPU
Or even hook the call from task manager that gets the CPU %, returning a sine result instead.
With the literally hundreds (thousands?) of threads a PC runs today, the only way I can think to even come close would be to poll CPU usage as fast as possible, and if the usage% was below where it should be on the curve, to fire off a short method that just churns numbers. That will at least bring the typical low usage UP where needed, but I can't think of a good way to LOWER it without somehow taking control of other threads, and doing something such as forcing thier priority lower.
Something like this:
while(true)
{
for(int i=0;i<360;i++)
{
// some code to convert i into radians if needed
...
Thread.Sleep(Math.Sin(i)*something_that_makes_it_noticeable_number_of_ms+something_that_makes_it_non_negative)
// some work to make cpu busy, may be increased to bigger number to see the influence on the cpu.
for(j=0;j<100;j++);
}
}

Resources