Stop weapon clipping

WeaponCollision.cs

Size: 2.54 KB

You need to login to download this file.

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.

  1. Create a layer where you want the fps object to sway away from
  2. Add the WeaponCollision.cs script to the weapon object

  3. Give your character 2 colliders:

    1. 1 wider,

    2. 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:

  1. LayerMask obstacleLayer: This variable defines the layer for obstacles. It's used to filter the objects that the raycast will interact with.

  2. rotationAngleX, rotationAngleZ: These variables determine the angles by which the weapon should rotate around the X and Z axes when it encounters an obstacle.

  3. rotationSpeed: This variable controls the speed at which the weapon rotates and moves when encountering an obstacle.

  4. moveAmountForward, moveAmountDown: These variables determine how much the weapon should move forward and downward when it encounters an obstacle.

  5. raycastDistance: This variable defines the maximum distance for the raycast to detect obstacles.

  6. originalRotation, targetRotation: These variables store the original and target rotations of the weapon.

  7. originalPosition, targetPosition: These variables store the original and target positions of the weapon.

  8. 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.

recommended