简体   繁体   中英

unity 3d make object follow player

I want to make a robot on unity3D. I want to make the gripper of the robot when collide with object attach the gripper. So the object will follow the gripper.

What will be added to this script in order to make some thing like this?

private Rigidbody gripper;

void Start() 
{
   gripper_part01 = GetComponent<Rigidbody>();
}

void Update() 
{
   if (Input.GetKey("a")) 
       gripper.AddForce(transform.forward * 100);
}

void OnCollisionEnter(Collider obj1) 
{
   // how to make obj1 follow the gripper
}

It can be done by various methods. But the simplest would be making the obj1 child of gripper as soon it collides.

code will look some thing like this

void OnCollisionEnter(Collider obj1) 
{
   // how to make obj1 follow the gripper
   obj1.transform.parent = gripper.transform;
}

Look into the state machine pattern

http://gameprogrammingpatterns.com/state.html

You'll want to create 2 states:

  1. Not Following(Default)
  2. Following

When the player enters the collider, switch the state to following. I'm not going to write you an entire state machine/state switching architecture for you to copy & paste, but I can tell you that you're going to want to make the states themselves a MonoBehavior class, and the actual StateMachine will not have any parent classes and will be attached to the object's controllers.

Then, you'll want to keep track of the player's coordinates like so

Vector3 playerPosition;

void OnCollisionEnter(Collider obj1)
{
    if(obj1.gameObject.tag == "Player"){
        playerPosition = obj1.transform.position;
        myStateMachine.switchState("Follow"); //obviously replace this with your own state machine code
    }
}

Make sure the player's gameObject actually has the "Player" tag in the Unity editor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM