【问题标题】:Projectiles spawning with incorrect trajectory以错误轨迹生成的弹丸
【发布时间】: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 效果会反转,并且只能按照我输入的方向正确射击,但我不知道如何让它正确射击各个方向。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    我会保留对射弹发射方向的引用,然后根据该方向移动每一帧。所以在我们Instantiate射弹之后,我们根据枪/玩家的旋转计算方向向量。以下代码应该完全符合您的要求,但由于我目前正在使用我的手机,因此未经测试!希望这会有所帮助!

    在弹丸内部。

    public Vector3 directionFired;
    

    里面的枪。

    GameObject proj = Instantiate(projectile, shotPoint.position, transform.rotation);
    proj.directionFired = Quaternion.Euler(transform.rotation) * Vector3.forward;
    timeBtwShots = startTimeBtwShots;
    

    内部射弹更新

    transform.Translate(directionFired * pSpeed * Time.deltaTime)
    

    【讨论】:

    • 嗨!很抱歉回复晚了,但要么我解释错了,要么代码错误,因为对于“Inside Gun”代码,它给了我 12 条错误消息。它们是(按顺序)代码的第二行:类、结构或接口成员声明中的无效标记“=” X2 无效标记“(”元组必须包含至少两个元素语法错误,“(”预期)预期第三行代码:类、结构或接口成员声明 X2 中的无效标记“=” 类、结构或接口成员声明 X2 中的无效标记“;”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 2013-11-10
    相关资源
    最近更新 更多