首页 > 解决方案 > 如何根据鼠标指针位置从屏幕中心向某个方向启动实例化对象?

问题描述

我正在创建一个简单的游戏,您被锁定在屏幕中央,并且必须在它们向您移动时射击。我目前面临的问题是我无法向鼠标光标的方向发射子弹。目前,我的代码看起来像这样

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour {

    PlayerScript playerScript;
    public float xVel;
    public float yVel;
    public float direction;

    private void Awake()
    {
        playerScript = FindObjectOfType<PlayerScript>();
        //playerScript.AngleDeg is the direction the player is facing (based on mouse cursor)
        transform.rotation = Quaternion.Euler(0, 0, playerScript.AngleDeg);

        direction = transform.rotation.z;

        //from the unit circle (x = cos(theta), y = sin(theta)
        xVel = Mathf.Cos(direction *  Mathf.PI);
        yVel = Mathf.Sin(direction *  Mathf.PI);

    }

    void Update () {
        transform.position += new Vector3(xVel,yVel,0);
    }
}

目前,当我运行代码时,子弹以一个角度射击,当玩家侧向时,子弹的方向是正确的,但当垂直定向时,完全偏离了 45 度。

标签: c#unity3d2d

解决方案


将此作为组件附加到您实例化的子弹对象上,它应该可以工作。

    Transform playerTransform;
    float bulletSpeed;
    Vector3 directionToShoot

    void Start()
    {
    playerTransform = FindObjectOfType<PlayerScript>().gameObject.transform;
    bulletSpeed = 3f;
    //Direction for shooting
    directionToShoot = playerTransform.forward - Camera.main.ScreenToWorldPoint(Input.mousePosition);
    }

    void Update()
    {
    //shoot
    transform.Translate(directionToShoot * bulletSpeed * Time.deltaTime);
    }

推荐阅读