Hello everyone here,
First time posting in this forum.
So, I am working on a snake like movement, where a number of balls follows the first ball in a line.
I modified a bit a code I found some weeks ago in youtube video, but I can not get the movement, that one ball follows the exact line. I spawn every bodypart via an Integer. Every balls (i) goes to the position of the one in front of him (i-1). This way I get the movement I was hoping for, but not exactly the way I was imagining.
The movement of the balls becomes to fluent and I would like it to be more strict. How can I accomplish this? Any suggestions?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SnakeMovement : MonoBehaviour
{
public List<Transform> BodyParts = new List<Transform>();
public float mindistance = 0.25f;
public float speed = 1;
public float rotationspeed = 50;
public int beginSize;
public GameObject bodyprefab;
public GameObject mainbody;
private float dis;
private Transform curBodyPart;
private Transform PrevBodypart;
void Start()
{
for (int i = 0; i < beginSize - 1; i++) {
AddBodyPart();
}
}
void Update()
{
Move();
}
public void Move()
{
float curspeed = speed;
//BodyParts[0].Translate(this.transform.position * curspeed * Time.smoothDeltaTime, Space.World);
//for (int i = 1; i< BodyParts.Count; i++) {
// curBodyPart = BodyParts[i];
// PrevBodypart = BodyParts[i - 1];
// dis = Vector3.Distance(PrevBodypart.position, curBodyPart.position);
// Vector3 newpos = PrevBodypart.position;
// newpos.y = BodyParts[0].position.y;
// float T = Time.deltaTime * dis / mindistance * curspeed;
// if (T > 0.5f)
// T = 0.5f;
// curBodyPart.position = Vector3.Slerp(curBodyPart.position, newpos, T);
// curBodyPart.rotation = Quaternion.Slerp(curBodyPart.rotation,PrevBodypart.rotation, T);
//}
for (int i = 1; i < BodyParts.Count; i++) {
curBodyPart = BodyParts[i];
PrevBodypart = BodyParts[i - 1];
dis = Vector3.Distance(PrevBodypart.position, curBodyPart.position);
Vector3 newpos = PrevBodypart.position;
float T = Time.deltaTime * dis / mindistance * curspeed;
if (T > 0.5f)
T = 0.5f;
BodyParts[0].position = Vector3.Slerp(mainbody.transform.position, newpos, T);
curBodyPart.position = Vector3.Slerp(curBodyPart.position, newpos, T);
curBodyPart.rotation = Quaternion.Slerp(curBodyPart.rotation, PrevBodypart.rotation, T);
}
}
public void AddBodyPart() {
Transform newpart = (Instantiate(bodyprefab, BodyParts[BodyParts.Count -1].position, BodyParts[BodyParts.Count - 1].rotation) as GameObject).transform;
newpart.SetParent(transform);
BodyParts.Add(newpart);
}
}