How to place an object at the centre of another and move it along.

For a skating game I am doing raycasting to detect the player being ontop of a mesh with the tag “Metal Rail”. The code I am currently writing needs to:

  • Position the player at the middle of the rail
  • In the direction the player is moving, push them along the rail at the current moving speed multiplied by another factor.

So skateSpeed is the speed we normally moving and grindSpeed is that extra boost of speed we get. What I am having trouble with is moving the player along and placing the player in the middle of the rail so we’re not grinding far off the mesh. Here is my attempt in C#:

//Grinding
		
		  Vector3 down = transform.TransformDirection(Vector3.down);
		 if (Physics.Raycast(transform.position, down, out hit))
		{
			if (hit.collider.CompareTag("MetalRail"))
			{
				print("We're grinding!!!");
			transform.Translate(0,Vector3.forward * Time.deltaTime * skateSpeed * grindSpeed,0);
				transform.rotation = collider.GetComponent.rotation;
			Grind(); //Animation cues
			}
			
			
		}

Please assist me in correctly performing the translation to move the player along and position the player at the centre of the rail. Many thanks!

Let’s say your player’s local x is the axis pointing forward. Couldn’t you just move him along his z axis to center him once he’s on the rail.

if (hit.collider.CompareTag("MetalRail")) {
   Vector3 newZ = new Vector3(transform.position.x, transform.position.y, hit.collider.transform.position.z);
   transform.position = newZ;
}