How to properly make an object follow the edge of another object?
I want to have a cover system which works so that if the player is near a object big enough and presses the crouch key he hides behind that object basically meaning he is in a crouch animation and can move along it with A and D keys to side to side (Picture), I made this script but with this the speed variable for the movement while crouched doesn't seem to be taken into account, the thing causing it is the transform.position = coverPos;
line and I can't find any other way to make the player "snap" to the edge of the other object so any help? The raycasting/cover "snapping" code:
if (Physics.Raycast(coverBottom.position, coverBottom.TransformDirection(Vector3.forward), out hitB, 1.5f, layerMask))
{
coverPosition = hitB.point + hitB.normal * 0.3f;
coverPosition.y = 0f;
if (inCover)
{
Vector3 lastNormal = Vector3.zero;
Vector3 coverPos = new Vector3(coverPosition.x, transform.position.y, coverPosition.z);
transform.position = coverPos;
transform.forward = -hitB.normal;
}
}
The player movement code: (There's lot more of course this is just that one part of it)
public float walkSpeed = 2;
public float runSpeed = 4;
public float crouchSpeed = 0.5f;
public float animationWalkSpeed = 1;
public float animationRunSpeed = 3;
public float animationCrouchSpeed = 0.5f;
else if (!inputController.Run)
{
if (inputController.Cover || inCover)
{
crouch = true;
playerAnimator.SetFloat("speed", animationCurrentSpeed);
decreaser = runSpeed;
decreaser = Mathf.Clamp01(Time.time - secondsTillMaxSpeed);
currentSpeed = Mathf.Lerp(walkSpeed, crouchSpeed, decreaser);
animationCurrentSpeed = Mathf.Lerp(animationWalkSpeed, animationCrouchSpeed, decreaser);
float yStore = moveDirection.y;
if (inCover && h > 0)
{
moveDirection = transform.right * currentSpeed * Time.deltaTime;
}
else if (inCover && h < 0)
moveDirection = -transform.right * currentSpeed * Time.deltaTime;
else if (!inCover && h != 0)
moveDirection = transform.forward * currentSpeed * Time.deltaTime;
moveDirection.y = yStore;
characterController.Move(moveDirection * Time.deltaTime);
}
}
Comment