【发布时间】:2019-10-28 07:03:55
【问题描述】:
我为枪和弹丸编写了一个脚本,但每当我开火时,它只会在我指向上方时朝正确的方向开火,如果我指向侧面,它会向下射击,如果我指向下方,它就会向上射击。
我一直在尝试获得一个简单的脚本,使枪旋转以面对鼠标(有效),然后在枪的射击中产生子弹,但是,当它们不朝上时会奇怪地产生,我'已经尝试更改具有脚本的对象,但没有别的,因为我不确定错误是什么。
枪脚本:
using UnityEngine;
using System.Collections;
public class Gun : MonoBehaviour
{
public float offset;
public GameObject projectile;
public Transform shotPoint;
private float timeBtwShots;
public float startTimeBtwShots;
private void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if (timeBtwShots <= 0)
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(projectile, shotPoint.position, transform.rotation);
timeBtwShots = startTimeBtwShots;
}
}
else
{
timeBtwShots -= Time.deltaTime;
}
}
}
弹丸脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour
{
public float pSpeed;
public float lifeTime;
public GameObject destroyEffect;
private void Start()
{
Invoke("DestroyProjectile", lifeTime);
}
private void Update()
{
transform.Translate(transform.up * pSpeed * Time.deltaTime);
}
void DestroyProjectile()
{
Destroy(gameObject);
}
}
我知道在射弹脚本中,我将 void 更新中的 transform.up 更改为 transform.right 或 left 效果会反转,并且只能按照我输入的方向正确射击,但我不知道如何让它正确射击各个方向。
【问题讨论】: