Stop weapon clipping
This script essentially ensures that when the weapon encounters an obstacle, it rotates and moves in response to avoid collision. It provides a smooth transition for the weapon's behavior when interacting with the game environment.
- Create a layer where you want the fps object to sway away from
-
Add the WeaponCollision.cs script to the weapon object
-
Give your character 2 colliders:
-
1 wider,
- 1 longer.
-
This will make sure the weapon will be in your collider and not be able to go through the wall!
Script
This script is designed to handle weapon collisions with obstacles in a Unity game. Let's break down the key components and functionality:
-
LayerMask obstacleLayer: This variable defines the layer for obstacles. It's used to filter the objects that the raycast will interact with.
-
rotationAngleX, rotationAngleZ: These variables determine the angles by which the weapon should rotate around the X and Z axes when it encounters an obstacle.
-
rotationSpeed: This variable controls the speed at which the weapon rotates and moves when encountering an obstacle.
-
moveAmountForward, moveAmountDown: These variables determine how much the weapon should move forward and downward when it encounters an obstacle.
-
raycastDistance: This variable defines the maximum distance for the raycast to detect obstacles.
-
originalRotation, targetRotation: These variables store the original and target rotations of the weapon.
-
originalPosition, targetPosition: These variables store the original and target positions of the weapon.
-
playerCamera: This variable holds a reference to the main camera.
Start():
- Saves the original rotation and position of the weapon.
- Finds the main camera.
Update():
- Checks if there is an obstacle in front of the weapon using a raycast from the player camera's position.
- If an obstacle is detected:
- Calculates the target rotation and position based on the specified angles and movement amounts.
- If no obstacle is detected:
- Resets the target rotation and position to their original values.
- Rotates the weapon towards the target rotation using Quaternion.Lerp for smooth rotation.
- Moves the weapon towards the target position using Vector3.Lerp for smooth movement.