问题
I am having difficulty chaining together some GameObjects to "Follow the leader".
This is what I am trying to accomplish:
Where there is a "head" object and it pulls the body
objects with it. Like a snake or centipede.
However, this is what is happening:
They all kinda follow the head and but they seem to move as a whole.
Can anyone see what I am doing wrong?
Here is my Centipede Object that the others classes inherit from. I started to tinker with the idea of just making the CentipedeObject move all of the independent GameObjects. But that didn't work.
CentipedeObject.cs
public abstract class CentipedeObject : MonoBehaviour {
[SerializeField]
private float moveSpeed = 1.5f;
public float MoveSpeed {
get {
return moveSpeed;
}
}
}
Here is the CentipedeHead that does the moving.
public class CentipedeHead : CentipedeObject {
private Rigidbody2D _body;
private Vector2 moveDirection = Vector2.zero;
private void Awake() {
_body = GetComponent<Rigidbody2D>();
_body.gravityScale = 0;
_body.constraints = RigidbodyConstraints2D.FreezeRotation;
}
private void Start() {
InvokeRepeating("ChangeDirection", 0, Random.Range(1.25f, 3.0f));
}
private void FixedUpdate() {
_body.velocity = moveDirection.normalized * MoveSpeed;
}
private void ChangeDirection() {
moveDirection = Vector2.zero;
switch (Random.Range(0, 4)) {
case 0:
moveDirection += Vector2.up;
break;
case 1:
moveDirection += Vector2.right;
break;
case 2:
moveDirection += Vector2.down;
break;
case 3:
moveDirection += Vector2.left;
break;
}
}
}
And the CentipedeBody part that should just follow the head or another body part.
public class CentipedeBody : CentipedeObject {
public GameObject objectToFollow;
private Vector3 followSize;
void Start() {
//Get the size of the object we are following
followSize = objectToFollow.GetComponent<SpriteRenderer>().bounds.size;
//Set initial distance
transform.position = objectToFollow.transform.position + followSize;
}
private void FixedUpdate() {
Vector3 followFromPosition = objectToFollow.transform.position + followSize;
transform.position = Vector3.MoveTowards(transform.position, followFromPosition, MoveSpeed * Time.deltaTime);
}
}
回答1:
I think the logic of updating the pixels is wrong. When the head moves one pixel left. You are making all other body parts move left by 1 pixel. Where as what you need to do is that (from your diagram) 2 takes the exact place where 1 was. 3 takes the place where 2 was and so on.
来源:https://stackoverflow.com/questions/46791141/gameobjects-following-a-leader-centipede-issue