unity3d - 子弹射不准
问题描述
我正在做一个 2d 游戏,它的动作和动作基于屏幕上的按钮。我射击时的子弹只是向左而不是向右,即使按下我的玩家向右走(游戏是在统一 2d 中制作的) 我怎样才能让子弹检测到标记的敌人?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class Character : MonoBehaviour
{
Rigidbody2D rb;
float dirX;
[SerializeField]
float moveSpeed = 5f, jumpForce = 600f, bulletSpeed = 500f;
bool facingRight = true;
Vector3 localScale;
public Transform barrel;
public Rigidbody2D bullet;
// Use this for initialization
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}
void FixedUpdate()
{
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
}
void Jump()
{
if (rb.velocity.y == 0)
rb.AddForce(Vector2.up * jumpForce);
}
void Fire()
{
var firedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
firedBullet.AddForce(barrel.up * bulletSpeed);
}
}
解决方案
命中检测
为了检测你是否用子弹击中了敌人,在你的子弹预制件中添加一个触发对撞机和一个脚本,其中包含以下代码:如果你用子弹击中敌人,这个例子将摧毁敌人的游戏对象。
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "enemy")
{
// Do your code
// For example
Destroy(collision.gameObject);
}
}
子弹旋转
关于你的另一个问题,你用桶.位置和桶.旋转来实例化子弹。当你改变方向时,你会改变枪管的旋转吗?
推荐阅读
- c# - 如何覆盖默认 JsonConverter(在属性中指定)
- amazon-s3 - NiFi数据插入s3子目录
- stored-procedures - 删除距当前时间 2 个月前最近访问的 Redshift 表
- javascript - 如何使用 Jest / Enzyme 模拟 onKeyDown 事件?
- javascript - 在 Angular 应用程序中使用 CKEditor5 自定义构建
- c# - 如何验证表达式是成员访问 lambda
- python - 无法从网站上抓取电话号码
- sql - 结合单行记录数的查询结果
- php - 我如何不断检查 php 中的 if 语句?
- javascript - 是否可以在javascript中重新分配const变量