Last active
June 19, 2021 14:02
-
-
Save mstfmrt07/84b18d0ce88c7b85dacb143b939647b7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public LayerMask contactWallLayer; | |
private void Roll(Direction direction) | |
{ | |
StartCoroutine(RollToDirection(direction)); | |
} | |
private IEnumerator RollToDirection(Direction swipeDirection) | |
{ | |
if(!isRolling) | |
{ | |
isRolling = true; | |
float angle = 90f; | |
Vector3 axis = GetAxis(swipeDirection); | |
Vector3 directionVector = GetDirectionVector(swipeDirection); | |
Vector2 pivotOffset = GetPivotOffset(swipeDirection); | |
//Relocate the pivot according to offset. | |
pivot.position = transform.position + (directionVector * pivotOffset.x) + (Vector3.down * pivotOffset.y); | |
float elapsedTime = 0f; | |
while (elapsedTime < rollDuration) | |
{ | |
elapsedTime += Time.deltaTime; | |
transform.RotateAround(pivot.position, axis, (angle * (Time.deltaTime / rollDuration))); | |
yield return null; | |
} | |
isRolling = false; | |
} | |
} | |
private Vector3 GetAxis(Direction direction) | |
{ | |
switch (direction) | |
{ | |
case Direction.Left: | |
return Vector3.forward; | |
case Direction.Up: | |
return Vector3.right; | |
case Direction.Right: | |
return Vector3.back; | |
case Direction.Down: | |
return Vector3.left; | |
default: | |
return Vector3.zero; | |
} | |
} | |
private Vector3 GetDirectionVector(Direction direction) | |
{ | |
switch (direction) | |
{ | |
case Direction.Left: | |
return Vector3.left; | |
case Direction.Up: | |
return Vector3.forward; | |
case Direction.Right: | |
return Vector3.right; | |
case Direction.Down: | |
return Vector3.back; | |
default: | |
return Vector3.zero; | |
} | |
} | |
private Vector2 GetPivotOffset(Direction direction) | |
{ | |
Vector2 pivotOffset = Vector2.zero; | |
Vector2 center = transform.GetComponent<BoxCollider>().size / 2f; | |
RaycastHit hit; | |
if (Physics.Raycast(transform.position, transform.up, out hit, 100f, contactWallLayer)) | |
{ | |
switch (hit.collider.name) | |
{ | |
case "X": | |
if (direction == Direction.Left || direction == Direction.Right) | |
pivotOffset = new Vector2(center.y, center.x); | |
else | |
pivotOffset = Vector2.one * center.x; | |
break; | |
case "Y": | |
pivotOffset = center; | |
break; | |
case "Z": | |
if (direction == Direction.Up || direction == Direction.Down) | |
pivotOffset = new Vector2(center.y, center.x); | |
else | |
pivotOffset = Vector2.one * center.x; | |
break; | |
} | |
} | |
return pivotOffset; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment