How to make viewmodels stop once hitting a wall

I am making a game where the character holds a flashlight, but the flashlight keeps clipping through walls once you go close to them, what I want to happen is the flashlight move back as you get closer to the wall, like in this video

Currently what i have tried is making the model go back to where it was before once hitting a wall, and then trying to move towards the camera in separate actions like first moving the x, checking, then moving the y, and so on. This almost worked but still had problems and also didn’t support moving the mouse, here is a video of what I have

I have also looked at other devfourm posts but they all seem to not directly this question.

How do I make the viewmodel stop moving/go back when it goes into walls?

A somewhat simplified way would be to:

  • Have a raycast go out forwards the length of the viewmodel. If there are any collisions, add a backwards offset to the viewmodel equal to goalLength - lengthUntilCollision.
  • Next, have a sideways raycast from the center of the viewmodel (in the direction out from the character) that goes the length that the viewmodel is wide. If it hits anything, use the same math to do an offset in this direction too and add it to the first offset
  • Finally apply both parts of the offset to the view model.

Note there are a lot of ways to do this. You could even physically simulate it (and even do IK on top of that!). The method above should work somewhat well.

You could also check if the viewmodel collides, and if it does, animate the character putting down the flashlight.

This is a common problem in FPS games, so if you search up “FPS weapon clipping” or “FPS viewmodel collision” etc on YouTube there are some examples of solutions.