【问题标题】:Bullet doesn't shoot right子弹射不准
【发布时间】:2022-04-09 17:35:10
【问题描述】:

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


    【解决方案1】:

    命中检测

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

    private void OnTriggerEnter2D(Collider2D collision)
        {
            if(collision.tag == "enemy")
            {
                // Do your code
    
    
                // For example
                Destroy(collision.gameObject);
            }
        }
    

    子弹旋转

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

    【讨论】:

      猜你喜欢
      • 2019-05-22
      • 2015-04-09
      • 2020-08-30
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多