【发布时间】:2015-07-20 04:08:19
【问题描述】:
我不想实现的是让我的炮台旋转并跟随“敌人”。
此刻它检测到了敌人,但它没有旋转,我不知道为什么。
它是我拖入的预制件,必须有更好的方法来做到这一点吗?请问大家有什么建议吗?
目前子弹永远不会触发,但是日志 Shoot and do...并且旋转不起作用。
这就是我所拥有的
using UnityEngine;
using System.Collections;
public class TurretController : MonoBehaviour {
public Rigidbody bulletPrefab;
private Transform target;
private GameObject bullet;
private float nextFire;
private Quaternion targetPos;
void OnTriggerEnter(Collider otherCollider) {
if (otherCollider.CompareTag("Enemy"))
{
Debug.Log ("in");
target = otherCollider.transform;
StartCoroutine ("Fire");
}
}
void OnTriggerExit(Collider otherCollider) {
if (otherCollider.CompareTag("Enemy"))
{
Debug.Log ("out");
target = null;
StopCoroutine("Fire"); // aborts the currently running Fire() coroutine
}
}
IEnumerator Fire()
{
while (target != null)
{
nextFire = Time.time + 0.5f;
while (Time.time < nextFire)
{
// smooth the moving of the turret
targetPos = Quaternion.LookRotation (target.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetPos, Time.deltaTime * 5);
yield return new WaitForEndOfFrame();
}
// fire!
Debug.Log ("shoot");
bullet = Instantiate(bulletPrefab, transform.position, transform.rotation) as GameObject;
//bullet.rigidbody.velocity = transform.forward * bulletSpeed;
}
}
}
我试图用这个来改变实例化部分
bullet = (GameObject)Instantiate(bulletPrefab, transform.position, transform.rotation);
bullet.GetComponent<Bullet>().target = target.transform;
但是我只是收到类似“InvalidCastException:无法从源类型转换为目标类型。 TurretController+c__Iterator0.MoveNext () (at Assets/Scripts/TurretController.cs:44)"
【问题讨论】: