如何根据鼠标指针位置从屏幕中心向某个方向启动实例化的对象?



我正在创建一个简单的游戏,你被锁定在屏幕中央,必须在它们向你移动时射击它们。 我目前面临的问题是我无法向鼠标光标的方向发射子弹。 目前,我的代码如下所示

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 度。

将其作为组件附加到实例化的项目符号对象,它应该可以工作。

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);
}

最新更新