Advertisement

How do I rotate an object over game time?

Started by December 19, 2020 08:03 PM
2 comments, last by darthdeus 3 years, 11 months ago

I wrote some fake world time, just a 24 hour cycle:

timeOfDay += Time.deltaTime * orbitSpeed;

int seconds = (int) (timeOfDay % 60);
int minutes = (int) (timeOfDay / 60) % 60;
int hours   = (int) (timeOfDay / 3600) % 24;

What's the best way I can have my sphere game object do a complete 360 spin with 24 in-game hours?

float y = Mathf.Lerp(a, b, timeOfDay);
transform.rotation = Quaternion.Euler(0f, y, 0f);

I can't wrap my head around this, but I'm thinking it's something along these lines, but I'm confused :( Any suggestions are appreciated!

None

u could give your game a “natural angular law of motion” -lol-

anyway, there are various ways about it…

all u need is to define an angular speed like it is for Earth which takes approx 86400sec per day to fully rotate once about its polar axis at the angular speed of 7.2e-5 radians per sec;

so each second, Earth rotates by:

1sec → 7.2e-5 rad = (7.2e-5 * 180 / pi) = 4.125e-3 degrees (approx)

proof:

TotalTimePerDayToCompleteOrbit = 86400 sec/day
total rotation (aka revolution) after a day = 86400 * 4.125e-3 = 356 degrees (approx)

so if your set your orbitSpeed to:

//pseudo 

init() 
{
	orbitSpeed = ... rad/s
 	
 	rot = quat.euler(0,0,0)) // <--- start with no rotation 0 radian
 	...
}

update()
{
	...
	// then each time you clock a second, advance your rotation by orbitSpeed amount
	acc_time_in_msec += deltatime_in_msec
	
	if (acc_time_in_msec >= 1000.0)
	{
		rot = quat.euler(0, orbitSpeed, 0) * rot // <--- choose the correct mult order for your math lib
		rotate_sphere(rot)
		acc_time_in_msec = 0
	}
	...
}

render()	
{
 ...
 render_rotated_sphere()
 ...
}

things to bear in mind:

  • i'm coding this for the top of my head as usual, hopefully i remembered well ?
  • if quat.euler(…) expects degrees then convert your orbitSpeed to degrees first before passing it in ( I have assumed radians );
  • note that rot is the result of the previous rot multiplied by the new rot, maybe in your maths lib you don't even need the multiplication? so see what works for you (consider the mult order as well, could be the other way round for you)
  • finally, u may want to set an orbitSpeed less than that of Earth's to fake it in-game ? otherwise you'll wait a day for a complete revolution -boom-

hope this helps

have fun ?

Advertisement

I'd suggest looking at the unit circle and trig functions (sin/cos). 360 degrees or 2pi radians is a full circle, and if you want to map “24h” to a full circle, you just need to convert between the two, so 24h = 360, 12h = 180, etc. … then the x/y position is just obtained with cos(theta) and sin(theta).

created Hell Loop - indie pixel art tower defense platformer

This topic is closed to new replies.

Advertisement