实例化椰子物体及注意事项

来源:互联网 发布:淘宝图片发布行为准则 编辑:程序博客网 时间:2024/04/28 11:07


using UnityEngine;
using System.Collections;


public class CoconutThower : MonoBehaviour {

public AudioClipthrowSound;
public Rigidbody coconutPrefab;
public float throwSpeed = 30.0f;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
//判断是否 按下鼠标左键
if (Input.GetButtonDown ("Fire1")) {
//播放声音片段,播放前需要给这个依附的物体添加AudioSource组件
GetComponent<AudioSource>().PlayOneShot(throwSound);
//实例化一个椰子物体 作为刚体
Rigidbody newCoconut = Instantiate(coconutPrefab,transform.position,transform.rotation) as Rigidbody;
//通过代码判断这个生成的物体是否具有刚体Rigidbody属性,如果没有该属性,则需要添加,这是为了避免游戏发生低级错误
if (newCoconut.GetComponent<Rigidbody>()== null) {
newCoconut = gameObject.AddComponent<Rigidbody>();
}
//给新生成的椰子物体添加名字
newCoconut.name = "coconut";
//给新生成的椰子物体添加速率,这个参数带有方向和速度的属性;可以使物体沿固定方向以设定速率运动
newCoconut.velocity = transform.forward * throwSpeed;
//忽略人物角色与生成的椰子物体之间的碰撞 transform.root.是寻找玩家控制器;忽略碰撞的具体介绍见下面;
Physics.IgnoreCollision (transform.root.GetComponent<Collider>(), newCoconut.GetComponent<Collider>(), true);


}
}




0 0