How can I make my player 'stick' to a fixed object

Hi, I am experimenting with a cover system for an FPS. Although it seems to be a VERY common question, and there are hundreds of references to such a system, nothing actually matches my particular requirements :frowning:

I have a simple movement script and a simple CoverDetect script. The CoverDetect script casts a ray out from the front of my Player, and returns a RayCastHit object and two variables indicating that cover is possible and the type of cover. For example, some objects in my level are tagged as “CoverStanding”. In other words, my player can enter cover behind this object while remaining in a standing position. I have other objects similarly tagged: “CoverCrouch” and “CoverProne”. As my player explores the map, the CoverDetect script correctly identifies each object as one of the three cover types (by displaying it in GUIText).

When the player object is in a potential cover position and the user presses space, I want to constrain the movement of player object to plane of the object that the CoverDetect script has returned.

I have tried two techniques - both have failed:

  1. I simply set the tranform.z to zero. This actually works quite well, but only for cover objects oriented exactly to the World Coordinates.
  2. I’ve dynamically created a FixedJoint and joined the two rigid bodies together. This results in the player simply ‘picking up’ the cover object and walking around with it! Not quite what I intended LOL.

My guess is that I need to match the player coordinate system to the local coordinate system of the object returned by the CoverDetect script and then proceed from there - however, I have not been able to find any help on how to do this.

Let me thank you all for your patience - please forgive me if this has already been documented somewhere else - I have searched extensively I promise :slight_smile:

Your assistance is much appreciated.

PS. Because my searching on this topic has been so frustrating, once I have cracked the problem, I intend to document it myself and make it available to the community.

Without source, I have to be a bit hand-wavy. I’m looking at the core of your question as:

I want to constrain the movement of
player object to plane of the object
that the CoverDetect script has
returned.

It can be done arbitrarily, but it is likely easiest done using the transform of the cover object. And it make it much easier if the normal to the plane of movement is always the same local axis. Say you want to allow the object to move along the x and y of the cover object, but not the local z, and you have the proposed move direction:

moveDir = coverObject.InverseTransformDirection(moveDir);
moveDir.z = 0.0;
moveDir = coverObject.TransformDirection(moveDir);

You convert the move direction into the local coordinates of your cover object, eliminate one axis of movement and then convert it back.