I am making a 2d character controller based around ray collision detection for the levels. When I move in the positive direction along the x axis the math works perfectly when colliding with anything. When my velocity is negative the position of the ray isn’t properly set and it causes player to spaz out, jittering near the collision. The only thing that is different when the velocity is negative is that I multiply the ray’s x variable by -1. For some reason it offsets the ray more than it should. Here is the code for the horizontal collision check:
void HorizontalCollisionCheck(ref Vector3 rawVelocity)
{
int directionCheck = (rawVelocity.x<0)?-1:1;
Vector2 rayPosition = new Vector2(transform.position.x,
transform.position.y);
int sidesCount = sides.nestedRay2DProperties.Count;
Debug.Log(sidesCount);
for (int i = 0; i < sidesCount; i++)
{
Vector2 tempPos = rayPosition;
if (directionCheck>0) {
tempPos.x += sides.nestedRay2DProperties[i].rayPositionOffset.x;
tempPos.y += sides.nestedRay2DProperties[i].rayPositionOffset.y;
}
if (directionCheck<0) {
tempPos.x -= sides.nestedRay2DProperties[i].rayPositionOffset.x;
tempPos.y += sides.nestedRay2DProperties[i].rayPositionOffset.y;
}
// tempPos.x += sides.nestedRay2DProperties[i].rayPositionOffset.x * directionCheck;
// tempPos.y += sides.nestedRay2DProperties[i].rayPositionOffset.y;
// Vector2 tempPos =
// new Vector2(rayPosition.x +
// sides.nestedRay2DProperties[i].rayPositionOffset.x,
// rayPosition.y + sides.nestedRay2DProperties[i].rayPositionOffset.y);
//tempPos.x=tempPos.x*directionCheck;
Ray2D r = new Ray2D(tempPos, Vector2.right * directionCheck);
RaycastHit2D hit = Physics2D.Raycast(r.origin, r.direction,
velocity.x + sides.nestedRay2DProperties[i].raylength,
platformLayerMasks);
if (hit)
{
Debug.Log(velocity);
if (directionCheck<0)
{
//rawVelocity.x =(hit.point.x-r.origin.x)-(-sides.nestedRay2DProperties[i].raylength);
rawVelocity.x =(hit.point.x-r.origin.x)-(sides.nestedRay2DProperties[i].raylength*directionCheck);
//rawVelocity.x = 0;
}
if (directionCheck>0)
{
rawVelocity.x =(hit.point.x-r.origin.x)-sides.nestedRay2DProperties[i].raylength;
//rawVelocity.x = 0;
}
Debug.Log(hit.point);
Debug.Log(tempPos);
//Debug.Log(r.origin);
//Debug.Log(rawVelocity.x);
break;
}
}
}