Skip to content

Instantly share code, notes, and snippets.

@Alex-Galbraith
Last active March 8, 2019 05:13
Show Gist options
  • Save Alex-Galbraith/1b7b61540caad45525fb7f69a37ff847 to your computer and use it in GitHub Desktop.
Save Alex-Galbraith/1b7b61540caad45525fb7f69a37ff847 to your computer and use it in GitHub Desktop.
//Allocate space for our hits outside the function so that
//garbage collection doesnt have to repeatedly collect our hits
RaycastHit2D[] hits = new RaycastHit2D[1];
/// <summary>
/// Move in the specified direction, modifying velocity if we hit something
/// </summary>
/// <param name="velocity">Current veloctity</param>
/// <param name="remainingDelta">Movement to do in this frame</param>
/// <param name="newVelocity">Output new velocity</param>
/// <param name="newRemaining">Remaining movement this frame after moving</param>
/// <param name="hit">Output hit</param>
/// <param name="normalBias">How much should we adjust the final position by the normal direction of the hit</param>
/// <returns>true if we need to cast again, false otherwise.</returns>
bool CastAndMove(Vector2 velocity, Vector2 remainingDelta, out Vector2 newVelocity, out Vector2 newRemaining, out RaycastHit2D hit, float normalBias = 0.05f) {
//save initial position
Vector3 opos = rigidbody.position = transform.position;
//Collider cast
int hitCount = collider.Cast(remainingDelta, terrainFilter, hits, remainingDelta.magnitude);
hit = hits[0];
//If we didnt hit, just move
if (!hit) {
transform.Translate(remainingDelta);
newRemaining = Vector3.zero;
newVelocity = velocity;
return false;
}
//We did hit
else {
//Move the character
transform.position = hit.centroid + normalBias * hit.normal;
//Remove moved vel from remaining
newRemaining = remainingDelta + (Vector2)(opos - transform.position);
newVelocity = velocity - (Vector2.Dot(velocity, hit.normal) * hit.normal);
//Make remaining velocity change when hitting something
newRemaining = newRemaining - Vector2.Dot(newRemaining, hit.normal) * hit.normal;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment