首页 > 解决方案 > 子弹射不准

问题描述

我正在做一个 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);
    }
}

标签: unity3d

解决方案


命中检测

为了检测你是否用子弹击中了敌人,在你的子弹预制件中添加一个触发对撞机和一个脚本,其中包含以下代码:如果你用子弹击中敌人,这个例子将摧毁敌人的游戏对象。

private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.tag == "enemy")
        {
            // Do your code


            // For example
            Destroy(collision.gameObject);
        }
    }

子弹旋转

关于你的另一个问题,你用桶.位置和桶.旋转来实例化子弹。当你改变方向时,你会改变枪管的旋转吗?


推荐阅读