PopeSpaceous / Solitary

A 2D Puzzle Platformer built with Unity
Other
6 stars 10 forks source link

Use variables and Mathf.Abs() for checking position between source and target tangrams #141

Open jespirit opened 5 years ago

jespirit commented 5 years ago

Use xPositionDelta and yPositionDelta variables as well as a little bit of algebra for checking if the source (moveable) tangram lies within the x-axis delta or y-axis delta of the target (outline) tangram.

Before:

//Check if x coordinate is in the tolerance range
if (this.myTanPosition.x * 10 < (xInTan * 10 + 3) && this.myTanPosition.x * 10 > (xInTan * 10 - 3)) {
    //Check if y coordinate is in the tolerance range
    if (this.myTanPosition.y * 10 < (yInTan * 10 + 3) && this.myTanPosition.y * 10 > (yInTan * 10 - 3)) {

Update:

private float xPositionDelta = 3.0f;
private float yPositionDelta = 3.0f;

//Check if x coordinate is in the tolerance range
if (Mathf.Abs(this.myTanPosition.x * 10 - xInTan * 10) < xPositionDelta) {
    //Check if y coordinate is in the tolerance range
    if (Mathf.Abs(this.myTanPosition.y * 10 - yInTan * 10) < yPositionDelta) {

Math:

s = this.myTanPosition.x  // source x
d = xInTan  // destination x

= 10s > (10d - 3) && 10s < (10d + 3)
// rearrange 10s to be in the middle of an inequality
= 10d - 3 < 10s < 10d + 3
// subtract -10d from all expressions
= -3 < 10s - 10d < 3
// use absolute
= |10s - 10d| < 3

= |x| < 2
= -2 < x < 2

Also, why do you multiply by 10?