c# - 在 Unity 中发射弹丸
问题描述
我正在尝试使用 Unity 在游戏中构建武器。我的子弹产生了,但我似乎无法在实例化时施加力以使它们真正开火。
我的武器脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Weapon : MonoBehaviour {
public Rigidbody2D projectile;
public float forceMultiplier;
public Vector2 direction;
public Transform firePoint;
private float timeBtwShots;
public float startTimeBtwShots;
public void Fire(float force, Vector2 direction)
{
Instantiate(projectile, firePoint.position, transform.rotation);
projectile.AddForce(direction * force);
}
// Update is called once per frame
void Update () {
if (timeBtwShots <= 0)
{
if (Input.GetKeyDown(KeyCode.Return))
{
Fire(forceMultiplier, direction);
timeBtwShots = startTimeBtwShots;
}
}
else
{
timeBtwShots -= Time.deltaTime;
}
}
}
解决方案
您需要将力添加到生成的对象而不是预制件。你的代码应该是这样的:
public void Fire(float force, Vector2 direction)
{
Rigidbody2D proj = Instantiate(projectile, firePoint.position, transform.rotation);
proj.AddForce(direction * force);
}
推荐阅读
- python - 如何有效地计算多个列表的共现计数?
- amazon-ec2 - 尽管命令正在 AWS EC2 实例上的终端上运行,但 Cron 作业无法正常工作
- c++ - 用于从 Java 移植到 C++ 的文本字符串的 3 路基数快速排序
- python - FFMPEG:向视频添加多个垂直堆叠的绘图文本
- javascript - Javascript 24 小时到 12 小时
- java - 使用 Java Stream 从文件中实例化对象
- python - 如何在值内转义分隔符
- android-studio - Error when downloading a file with url into internal storage Android Studio
- gmail-api - 为什么我的员工在通过 PipelineDeals 发送电子邮件时收到此消息?
- powerquery - Power Query:查找组内的百分位数