The recoil back and forward was made using coroutine and Lerp like this,
Vector3 recoilBack = new Vector3(currentGun.retroActionForce, originPos.y, originPos.z);
Vector3 retroActionRecoilBack = new Vector3(currentGun.retroActionFineSightForce, currentGun.FineSightOriginPos.y, currentGun.FineSightOriginPos.z);
if(!isfineSightMode)
{
currentGun.transform.localPosition = originPos;
// start recoil back and forward
while(currentGun.transform.localPosition.x <= currentGun.retroActionForce - 0.02f)
{
currentGun.transform.localPosition = Vector3.Lerp(currentGun.transform.localPosition, recoilBack, 0.4f);
yield return null;
}
// back to place
while(currentGun.transform.localPosition != originPos)
{
currentGun.transform.localPosition = Vector3.Lerp(currentGun.transform.localPosition, originPos, 0.1f);
yield return null;
}
}
The code above is the code that recoils back and forward.
but How do I make the camera recoil up?
I don’t think it uses a coroutine when moving the camera up.
please help…
From what I can see, it looks like you’re able to achieve recoil on the gun using coroutines and Lerp. If you want to achieve recoil for the camera, you can modify the camera’s position in a similar way. You can use a coroutine to move the camera up and then move it back to its original position. Here’s an example of how you could modify the code you shared to achieve camera recoil:
Vector3 recoilBack = new Vector3(currentGun.retroActionForce, originPos.y, originPos.z);
Vector3 retroActionRecoilBack = new Vector3(currentGun.retroActionFineSightForce, currentGun.FineSightOriginPos.y, currentGun.FineSightOriginPos.z);
Vector3 cameraRecoilUp = new Vector3(originPos.x, originPos.y + 0.2f, originPos.z);
if(!isfineSightMode)
{
// recoil back and forward for the gun
currentGun.transform.localPosition = originPos;
while(currentGun.transform.localPosition.x <= currentGun.retroActionForce - 0.02f)
{
currentGun.transform.localPosition = Vector3.Lerp(currentGun.transform.localPosition, recoilBack, 0.4f);
yield return null;
}
// back to place
while(currentGun.transform.localPosition != originPos)
{
currentGun.transform.localPosition = Vector3.Lerp(currentGun.transform.localPosition, originPos, 0.1f);
yield return null;
}
// recoil up and back for the camera
Vector3 cameraOriginPos = Camera.main.transform.position;
while(Camera.main.transform.position.y <= cameraRecoilUp.y)
{
Camera.main.transform.position = Vector3.Lerp(Camera.main.transform.position, cameraRecoilUp, 0.1f);
yield return null;
}
while(Camera.main.transform.position != cameraOriginPos)
{
Camera.main.transform.position = Vector3.Lerp(Camera.main.transform.position, cameraOriginPos, 0.1f);
yield return null;
}
}