Friday, 9 April 2010

Mass counteraction chip

In the course of making contraptions in Garry's Mod, you notice very quickly that the heavier something is, the stronger the connections it has to other things, especially with ballsockets and welds. The trouble then is that, when you're making an intricate contraption, having very heavy objects involved can throw off the balance and mechanics inherent in it.

Therefore, we need a way to have a heavy object not act like a heavy object, we need to counteract the mass. To do this, we need to oppose the gravity that the Source engine places on it based on its mass, and for that we need the tick rate of the server.

Unfortunately, there is no expression 2 function presently that returns the tick rate, but there is a very simple calculation we can do to find out. ApplyForce codes need to run per tick to be fully functional, so we have the tick running on a tick-by-tick basis anyway. We can also retrieve the time that has passed on the server with curtime(). This means we can tell how much time has passed between ticks by checking the time in two side-by-side tick-speed operations. The difference then is X, and if we have 1/X we get the number of ticks that occurs within one second on the server, the tick rate. From there, it's a simple matter of gravity()/(1/X) to get the amount of force per unit of mass in an entity that is being exerted by gravity on it, Y.

And then, simply, applyForce upwards by vec(0,0,Mass*Y)*Z, Z being the percentage of the entity's mass that we want to counteract.

And now the code:
@persist S AG E:entity

if(first()){
runOnTick(1) #Run chip every tick
S=curtime() #Start time
E=entity():isWeldedTo()
}
elseif(!AG){
T=curtime() #End time

#Separation (Time of 1 tick)
Dif=T-S

#Number of ticks in 1 second
Tick=1/Dif
AG=gravity()/Tick
}
else{
Comp=1
Vec=vec(0,0,E:mass()*AG)*Comp
E:applyForce(Vec)
}

No comments:

Post a Comment