Question by
VeryPoorProvider · Apr 04 at 10:50 PM ·
c#unity 5instantiatetransform3d
How to fix snake behavior in Unity3d?
I have a snake head and it has the following code to add a segment:
void AddPart()
{
Transform current = transform;
Tail tail = Instantiate(partFollowerPrefab, transform.position, partFollowerPrefab.transform.rotation).AddComponent<Tail>();
tail.transform.position = current.transform.position - current.transform.forward * 2;
tail.transform.rotation = transform.rotation;
tail.target = current.transform;
tail.targetDistance = 0.85f;
Destroy(tail.GetComponent<Collider>());
current = tail.transform;
}
}
Here is the segment code:
using UnityEngine;
public class Tail : MonoBehaviour
{
public Transform target;
public float targetDistance;
public void Update()
{
Vector3 direction = target.position - transform.position;
float distance = direction.magnitude;
if (distance > targetDistance)
{
transform.position += direction.normalized * (distance - targetDistance);
transform.LookAt(target);
}
}
}
Every time I add a segment, for some reason it spawns behind the head and not behind the next segment. Although if I do it through a loop, then everything works:
void AddPart()
{
Transform current = transform;
for (int i = 0; i < 3; i++)
{
Tail tail = Instantiate(partFollowerPrefab, transform.position, partFollowerPrefab.transform.rotation).AddComponent<Tail>();
tail.transform.position = current.transform.position - current.transform.forward * 2;
tail.transform.rotation = transform.rotation;
tail.target = current.transform;
tail.targetDistance = 0.85f;
Destroy(tail.GetComponent<Collider>());
current = tail.transform;
}
}
How to fix it?
Comment
Your answer
Follow this Question
Related Questions
Instantiating Objects randomly on a sphere with a set distance radius 0 Answers
How do i Instantiate sub-Points with in Multiple Points?? 0 Answers
I'm having a few issues with (Catmull)Splines that i need help with. 1 Answer
How do I Instantiate a prefab at the x axis position of where the UI button was clicked 1 Answer
How To Make An Object Appear In Front Of Player Without Cloning? 1 Answer