Prevent local movement of child with Rigidbody?
Hello!
I have the following setup: http://prntscr.com/u143b0
A sphere which acts as a collider and manages the behaviour of the NPC, and the NPC itself as a child. The sphere (parent) does all the thinking: when the player gets in range, it does what it needs to do, and the child is basically just a model, a visual thing. This particular NPC avoids the player at all costs and goes back to its original location once the player goes away.
Code for reference:
// Code that moves in FixedUpdate:
Vector3 center = gameObject.transform.position, avoidingTarget = PlayerGameObject.transform.position;
Vector3 dest = center + Quaternion.AngleAxis(180, Vector3.up) * (avoidingTarget - center);
MoveGameObjectTowards(gameObject, dest, avoidingSpeed);
// The method used
protected void MoveGameObjectTowards(GameObject gameObject, Vector3 position, int speed)
{
Vector3 desiredPosition = Vector3.MoveTowards(gameObject.transform.position, position, speed);
Vector3 smoothedPosition = Vector3.Lerp(gameObject.transform.position, desiredPosition, movementSmoothSpeed);
// Don't allow vertical movement.
smoothedPosition.y = gameObject.transform.position.y;
gameObject.transform.position = smoothedPosition;
}
However, I want the child to have collisions, so when the NPC moves away from the player and hits a wall, it does not go through walls.
This should be fairly simple, and it does work, but there is one issue: When the player comes closer while the NPC is hitting a wall, it doesn't move (I'd like it to still move away but it's fine for now I guess?), and when it resets back to its original position, everything is messed up and the model (child) isn't in the original position anymore.
This is because the rigidbody does some kind of local movement relative to the parent, so the model isn't in (0, 0, 0) anymore relative to the parent. Is there any way to prevent this from happening?
Of course I'd also appreciate some tips on how to do this thing better. Perhaps there's a better way to make my NPCs move away from the player while taking care of walls and such. Maybe I should use an AI/Navmesh instead? Any idea/tutorial?
Thank you very much.
Answer by MyPix · Aug 17, 2020 at 10:36 PM
I fixed this by switching to a NavMeshAgent and moving like this instead:
protected void MoveGameObjectTowards(GameObject gameObject, Vector3 position)
{
Agent.isStopped = false;
Agent.SetDestination(new Vector3(position.x, 0, position.z));
}
It's much more robust as it automatically avoids obstacles. There is no need for a rigidbody with this.
Your answer
Follow this Question
Related Questions
Move NPC on triggerEnter 0 Answers
Player Rotation and movement 0 Answers
Rigidbody First Person Controller Movement 0 Answers
Prevent rigidbody from sticking to wall? 0 Answers
Help with getting my player to stop moving when they hit a wall? 0 Answers