c# - 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(); 目标,它看起来完全像它应该的那样,但是子弹朝错误的方向移动。所以这行不通。
对不起我的英语不好和知识很少,任何帮助将不胜感激:)
解决方案
我不知道 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);
}
}
}
推荐阅读
- svelte - 如何将 dat.gui 库导入 Sapper/Svelte 项目?
- python-3.x - Jupyterhub - 无法更改开始目录
- python - 如何在python中访问csvfile的特定单元格
- python - 向 wtforms.widgets html5 NumberInput 添加最小值和最大值
- android - Naming convention for Web Apps added via the Add to Home Screen on iOS or Android?
- c - 我想将数据推送到二叉树中,但在 3 个输入后显示分段错误
- java - 不了解 ZGC 算法中有关颜色位的细节
- elasticsearch - ElasticSearch:是否可以将 dfs_query_then_fetch 与解释 API 一起使用?
- javascript - 有什么方法可以阻止 ECONNRESET 错误使我的机器人崩溃?
- javascript - Vuetify 文本字段:对值的更改不会持续存在(在模糊或焦点上丢失)