Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Walk inside a moving and rotating spaceship

Discussion in 'Scripting' started by Only4gamers, Oct 1, 2023.

  1. Only4gamers

    Only4gamers

    Joined:
    Nov 8, 2019
    Posts:
    311
    Hi there,

    I'm currently working on a game where player can explore a big spaceship and take control of it at any time. Fight takes place between ships at the same time, so there is no way to fake anything or keep the ship static. When the player is not in control, the AI takes over to guide the ship. The ship and player both are rigidbody objects, and I am using the MovePosition and MoveRotation to handle their movement and rotation.

    I have experimented with various approaches, such as:

    1) Attempt to synchronize the player's movement with that of the ship by adding a movement like this:

    Code (CSharp):
    1.  
    2. shipRB.MovePosition(shipRB.position + (speed * Time.deltaTime * transform.forward));
    3. playerRB.MovePosition(playerRB.position + (speed * Time.deltaTime * transform.forward));
    However, I don't know how to match ship's rotation for player.

    2) Another approach I tried is to create an empty transform as a child of the ship and control the movement of that child. Then, from the player's script, I replicate the child's movement. This method has shown promising results for both movement and rotation, but there are still some glitches when ship is rotating.

    I'm curious if anyone has any suggestions for a better solution to this problem. Your ideas would be greatly appreciated!
     
    Last edited: Oct 1, 2023
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    3,899
    Never tried this but what about making players children of the ship in the scene hierarchy? That's how you would do it without physics but I don't know if physics respect parenting.

    Make sure you replicate only the ship's rigidbody component and apply them to the player's rigidbody component and do so only in FixedUpdate. When you use or apply any position/rotation from or to a Transform you are bypassing physics and/or you are working with interpolated values.

    Given that the ship is probably pretty big you may want to enable Interpolation in its rigidbody. Especially if you observe the player making distinct jumps if the player is far from the center of rotation. You may also have to enable Interpolation on the player or possibly even interpolate yourself in Update between two FixedUpdate calls because the rigidbody interpolation may not apply in that case.