改变:在运动过程中设置了相对位置为(1,0,0).造成效果:旋转。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//在预制体实例化与C sharp类的方法之间出现了矛盾。
public class body_generate : MonoBehaviour
{
public GameObject prefab;
private Vector3 oldpos;
public Rigidbody rd;
//public Transform self;
List<GameObject> allbody;
// Start is called before the first frame update
void Start()
{
allbody = new List<GameObject>();
allbody.Add(this.gameObject);
rd = this.gameObject.transform.GetComponent<Rigidbody>();
// GameObject first = new GameObject("one");
// GameObject last = GameObject.Instantiate(prefab);
//last.AddComponent(typeof(Rigidbody));
// allbody.Add(last);
}
void Update()
{
Transform self = allbody[0].transform;
if (Input.GetKeyDown(KeyCode.Q))
{
//施加力的方式
oldpos = allbody[0].transform.position;
allbody[0].transform.position = oldpos + new Vector3(1, 0, 0);
/*
for (int i = 0; i < allbody.Count; i++)
{
oldpos = allbody[i].transform.position;
allbody[i].transform.position = oldpos + new Vector3(1, 0, 0);
}*/
if(allbody[allbody.Count - 1].transform.position[0] >= 1)
{
GameObject last = GameObject.Instantiate(prefab);
last.AddComponent(typeof(Rigidbody));
last.transform.parent = allbody[allbody.Count - 1].transform;
last.transform.localPosition = new Vector3(1, 0, 0);//设置位置 已实现不碰撞的固定位置的实例化。
last.transform.localRotation = Quaternion.identity;//设置角度
allbody.Add(last);
}
}
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
//Debug.Log(h);
//rd.AddForce(new Vector3(h, 0, v));
for (int i = 1; i < allbody.Count; i++)
{
allbody[i].transform.localPosition = new Vector3(1, 0, 0);
allbody[i].transform.localRotation = Quaternion.identity;
}
// GameObject third = GameObject.CreatePrimitive(PrimitiveType.Capsule);
}
}
也添加了testforce给预制体,test代码同上。复制在下面。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class testforce : MonoBehaviour
{
public Rigidbody rd;
// Start is called before the first frame update
void Start()
{
//this.gameObject.AddComponent(typeof(Rigidbody));
rd = this.gameObject.transform.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.K))
{
rd.AddForce(Vector3.right);
}
if (Input.GetKeyDown(KeyCode.H))
{
rd.AddForce(Vector3.left);
}
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
//Debug.Log(h);
rd.AddForce(new Vector3(h, 0, v));
}
}