目前,我的炮塔子弹跟随我的玩家。如何阻止它并让它只向我的玩家的最后位置前进?这是我目前的代码:
TurretBullet类:
using UnityEngine;
using System.Collections;
public class TurretBullet : MonoBehaviour {
private Transform target;
public float speed = 70f;
public void Seek(Transform _target) {
target = _target;
}
void Update() {
if (target == null) {
Destroy(gameObject);
return;
}
float distanceThisFrame = speed * Time.deltaTime;
Vector3 dir = target.position - transform.position;
if(dir.magnitude <= distanceThisFrame) {
HitTarget();
return;
}
transform.Translate(dir.normalized * distanceThisFrame, Space.World);
}
void HitTarget() {
Debug.Log("Player Hit!");
Destroy(gameObject);
}
}
我在某个地方看到了我需要使用的Vector3.forward
我尝试过尝试,但我无法使用它。我该如何正确实施呢?
炮塔类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Turret : MonoBehaviour {
private Transform target;
[Header("Attributes")]
public float range = 15f;
public float fireRate = 1f;
private float fireCountdown = 0f;
[Header("Unity Setup Fields")]
string playerTag = "Player";
public Transform partToRotate;
public float turnSpeed = 10f;
public GameObject bulletPrefab;
public Transform firePoint;
// Use this for initialization
void Start () {
InvokeRepeating("UpdateTarget", 0f, 0.5f);
}
void UpdateTarget() {
GameObject[] players = GameObject.FindGameObjectsWithTag(playerTag);
float shortestDistance = Mathf.Infinity;
GameObject nearestPlayer = null;
foreach(GameObject player in players) {
float distanceToPlayer = Vector3.Distance(transform.position, player.transform.position);
if(distanceToPlayer < shortestDistance) {
shortestDistance = distanceToPlayer;
nearestPlayer = player;
}
else {
target = null;
}
}
if(nearestPlayer != null && shortestDistance <= range) {
target = nearestPlayer.transform;
}
}
// Update is called once per frame
void Update () {
if(target == null)
return;
Vector3 dir = target.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * turnSpeed).eulerAngles;
partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);
if(fireCountdown <= 0f) {
Shoot();
fireCountdown = 1f / fireRate;
}
fireCountdown -= Time.deltaTime;
}
void Shoot() {
GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
TurretBullet bullet = bulletGO.GetComponent<TurretBullet>();
if (bullet != null)
bullet.Seek(target);
}
void OnDrawGizmosSelected() {
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, range);
}
}
答案 0 :(得分:1)
子弹跟随玩家,因为你每次都将子弹位置与当前玩家位置进行比较:
Vector3 dir = target.position - transform.position;
Transform
是一种引用类型,因此您的target
字段会获得相同的对象而不是其副本。
您应该复制原始位置。要制作副本,请指定target.position
- Vector3
为struct
,因此为值类型:
private Vector3 position;
public void Seek(Transform _target)
{
position = _target.position;
}
答案 1 :(得分:0)
也许是这样的? TurretBullet类:
private bool aimed = false;
public void Seek(Transform _target) {
if(!aimed){
target = _target;
aimed = true;
}
}