Files
Hexapod_Simulation_Unity/Assets/Walk2.cs
T

132 lines
3.2 KiB
C#
Raw Normal View History

2018-11-14 22:22:38 +01:00
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Walk2 : MonoBehaviour
{
public List<GameObject> legs = new List<GameObject>();
private List<Vector3> legsInitial = new List<Vector3>();
// Use this for initialization
void Start()
{
for (int index = 0; index < legs.Count; ++index)
{
legsInitial.Add(legs[index].GetComponent<Leg>().point);
2018-11-15 14:11:50 +01:00
step2.Add(0);
step3.Add(0);
2018-11-15 16:37:54 +01:00
step4.Add(new Vector3(0, 0, 0));
2018-11-14 22:22:38 +01:00
}
}
struct step
{
public float rotation;
public float height;
public bool inAir;
public step(float r, float h, bool i)
{
rotation = r;
height = h;
inAir = i;
}
}
// 1, 3, 5 -= 3
int offset(int i, int offset, int max)
{
return i - offset < 0 ? (max - (offset - i)) : i - offset;
}
step[] s = {
new step(-1, 0, false),
new step(0, -2, false),
new step(0, 0, false), // rest
new step(1, 0, false),
new step(1, 0, false),
new step(0, 0, false), // rest
new step(0, 2, false),
new step(-1, 0, true),
};
public int st = 5;
public int speed2 = 30;
int speed = 10;
public float rotation = 0;
int size = 8;
//public float walkspeed = 1;
2018-11-15 14:11:50 +01:00
private List<float> step2 = new List<float>();
private List<float> step3 = new List<float>();
2018-11-15 16:37:54 +01:00
private List<Vector3> step4 = new List<Vector3>();
2018-11-14 22:22:38 +01:00
// Update is called once per frame
void FixedUpdate()
{
if (speed <= 0)
{
2018-11-15 14:11:50 +01:00
if (st >= size - 1)
2018-11-14 22:22:38 +01:00
st = 0;
else
st++;
for (int index = 0; index < legs.Count; ++index)
{
int t = st;
if (index == 1 || index == 3 || index == 5)
{
t = offset(st, 4, size);
}
if (s[t].inAir == false)
{
2018-11-15 14:11:50 +01:00
step2[index] = (rotation * s[t].rotation) / speed2;
step3[index] = s[t].height / speed2;
2018-11-15 16:37:54 +01:00
step4[index] = new Vector3(0, 0, 0);
2018-11-14 22:22:38 +01:00
}
else
{
2018-11-15 16:37:54 +01:00
Vector3 t2 = legsInitial[index] - legs[index].GetComponent<Leg>().point;
step4[index] = t2 / speed2;
2018-11-14 22:22:38 +01:00
}
}
speed = speed2;
}
else
2018-11-15 14:11:50 +01:00
{
2018-11-14 22:22:38 +01:00
speed--;
2018-11-15 14:11:50 +01:00
makestep();
}
}
void makestep()
{
for (int index = 0; index < legs.Count; ++index)
{
2018-11-15 16:37:54 +01:00
if (step4[index] == new Vector3(0, 0, 0))
{
Vector3 n = legs[index].GetComponent<Leg>().getWorldPos();
n = Quaternion.Euler(0, step2[index], 0) * n;
n.y += step3[index];
// rotate x,y around rotation.
legs[index].GetComponent<Leg>().setWorldPos(n);
}
else
{
// return to home
legs[index].GetComponent<Leg>().point += step4[index];
}
2018-11-15 14:11:50 +01:00
}
2018-11-14 22:22:38 +01:00
}
}