Skip to content

Instantly share code, notes, and snippets.

@JISyed
Created September 5, 2013 04:05
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JISyed/6445974 to your computer and use it in GitHub Desktop.
Save JISyed/6445974 to your computer and use it in GitHub Desktop.
GameMaker script (GML) that makes an object gradually turn towards a target object at the specified speed. A tutorial explaining this code can be found here: http://jibransyed.wordpress.com/2013/09/05/game-maker-gradually-rotating-an-object-towards-a-target/
// gradually_turn.gml
// --------
// Gradually turns an object towards its target
//
// FORMAT:
// gradually_turn(objToTurn, target, turnSpeed, accuracy);
//
// <objToTurn> takes an object
// <target> takes an object
// <turnSpeed> takes a number
// <accuracy> takes a number between 0 and 1
//
var objToTurn = argument0;
var target = argument1;
var turnSpeed = argument2 / 100000; // Tweak the 100000 if you're not getting the desired results
var accuracy = clamp(argument3, 0.05, 0.95); // Don't want perfect accuracy or perfect inaccuracy
// Test if parameters are valid
if(!instance_exists(objToTurn)) return -1;
if(!instance_exists(target)) return -1;
// Reverse nomalize accuracy for calculations
accuracy = abs(accuracy - 1.0);
// Get the target direction and facing direction
var targetDir = point_direction(objToTurn.x, objToTurn.y, target.x, target.y);
var facingDir = objToTurn.direction;
// Calculate the difference between target direction and facing direction
var facingMinusTarget = facingDir - targetDir;
var angleDiff = facingMinusTarget;
if(abs(facingMinusTarget) > 180)
{
if(facingDir > targetDir)
{
angleDiff = -1 * ((360 - facingDir) + targetDir);
}
else
{
angleDiff = (360 - targetDir) + facingDir;
}
}
// Gradually rotate object
var leastAccurateAim = 30;
if(angleDiff > leastAccurateAim * accuracy)
{
objToTurn.direction -= turnSpeed * delta_time;
}
else if(angleDiff < leastAccurateAim * accuracy)
{
objToTurn.direction += turnSpeed * delta_time;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment