Unity3D通过碰撞拾取物体
发表于2019-01-21
注:此例子为2D场景
















原理:通过操控角色碰撞可拾取物体,通过按键确认拾取到角色指定位置。
具体代码实现
角色代码:
public class playctr: MonoBehaviour { public Transform pphead; //物体头部位置 private GameObject heads; //获取头部物体 bool gethead = false; //判断头部物体显示 void OnTriggerStay2D(Collider2D other) { if (other.gameObject.tag == "head") //碰撞的物体标签为头部时 { Debug.Log("please get E"); if (Input.GetKey(KeyCode.E)) //按下e装备物体 { other.gameObject.SetActive(false); //取消被拾取物体的显示 other.gameObject.tag = "phead"; //改变被拾取物的标签 gethead = true; //存在可装备头部物体 heads = other.gameObject; //获取头部物体 } } } void FixedUpdate() { if (gethead)//当存在可装备头部物体 { heads.gameObject.SetActive(true); //显示物体 heads.GetComponent<Transform>().position = pphead.GetComponent<Transform>().position;//将物体绑定在人物身上 } if (Input.GetKey(KeyCode.G) && heads.gameObject.tag == "phead")//当按下G且头部物体标签为phead时(简单说就是脱下装备) { gethead = false;//改变头部物体判断为不存在 } } }
被拾取物体代码
public class movv : MonoBehaviour { bool tlow = false; //装备存在物理属性掉落 public float stoptime; //改变装备为触发器等待时间 void FixedUpdate() { if (Input.GetKey(KeyCode.G) && this.gameObject.tag == "phead")//按下g脱掉装备 { this.gameObject.tag = "head"; tlow = true; } if (tlow) //装备变为存在物理属性 { this.GetComponent<BoxCollider2D>().isTrigger = false; this.GetComponent<Rigidbody2D>().gravityScale = 1; } if (this.GetComponent<Rigidbody2D>().gravityScale == 0) //装备的重力为0(改变为触发器) { this.GetComponent<BoxCollider2D>().isTrigger = true; } } void OnCollisionEnter2D(Collision2D collision) { if (collision.collider.tag == "land")//碰撞地面 { StartCoroutine(stop()); } } IEnumerator stop()//等待时间过后改变装备属性 { yield return new WaitForSeconds(stoptime); tlow = false; this.GetComponent<Rigidbody2D>().gravityScale = 0; } }
拾取过程:
1、开始时

物体属性



2、拾取物体至头部


3、脱下物体时




4、脱下后




角色设置:


相关解释:
1、拾取物体需要提前在角色设定好拾取后出现的位置。
2、需要设定被拾取物体改变为触发器的时间。假设没有设置时间,当被拾取物体碰撞地面立刻变为触发器,会保持原来的速度一直下落,所以设定这个时间相当于冷却,当被拾取物体碰撞地面,等待一段时间再改变属性为触发器。