首页 > 解决方案 > Unity 2D 中的自上而下拍摄无法如我所愿

问题描述

我正在 Unity 中制作一个 2D 自上而下的射击游戏。一切正常,当我尝试执行拍摄时问题就来了。

我对 Unity 和 C# 都没有经验,所以我主要使用教程来获取此代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class Bullet : MonoBehaviour
{
    public float speed = 20f;

    private Vector2 target;

    void Start()
    {
        target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }

    void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, target, speed * Time.deltaTime);
    }

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (!collision.name.Equals("Player") && !collision.name.Equals("Bullet(Clone)"))
        {
            Destroy(gameObject);
        }
    }
}

这是与子弹有关的一切,除了在点击时召唤它。这个脚本是子弹预制件上的一个对象,所以它会在子弹被召唤时运行。

我从中得到的结果与预期的一样——子弹在玩家身上产生并移动到我点击的地方,然后它停止了。然而,我想要它做的是继续朝着同一个方向前进,直到它碰到什么东西。

我尝试将 Vector2 目标乘以 10(或某个随机数),但是这样做时会发生非常奇怪的事情。当站在玩家生成和射击的地方时,它工作得很好。但是当我开始移动时,子弹会朝错误的方向飞去。如果我 Debug.Log(); 目标,它看起来完全像它应该的那样,但是子弹朝错误的方向移动。所以这行不通。

对不起我的英语不好和知识很少,任何帮助将不胜感激:)

标签: c#unity3d

解决方案


我不知道 Unity 的规格,但我认为这样的事情可以如你所愿:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class Bullet : MonoBehaviour
{
    public float speed = 20f;

    private Vector2 m_Direction;

    void Start()
    {
        // save direction by offsetting the target position and the initial object's position.
        m_Direction= Camera.main.ScreenToWorldPoint(Input.mousePosition) - this.transform.position;
    }

    void Update()
    {
        // this will cause to every frame the object's transform to be move towards the target position direction.
        transform.position = Vector2.MoveTowards(this.transform.position, this.transform.position + m_Direction, speed * Time.deltaTime);
    }

    void OnTriggerEnter2D(Collider2D collision)
    {
        if (!collision.name.Equals("Player") && !collision.name.Equals("Bullet(Clone)"))
        {
            Destroy(gameObject);
        }
    }
}

推荐阅读