c# - 如何根据鼠标指针位置从屏幕中心向某个方向启动实例化对象?
问题描述
我正在创建一个简单的游戏,您被锁定在屏幕中央,并且必须在它们向您移动时射击。我目前面临的问题是我无法向鼠标光标的方向发射子弹。目前,我的代码看起来像这样
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);
}
推荐阅读
- scala - 如何压缩两个 RDD (Scala)
- java - SQL:无法让 count(*) 工作 - 为什么会这样?
- c - 如何使用 epoll 从多个客户端接收多个缓冲区?
- neo4j - Neo 4j 中为节点定义的属性/属性的限制是什么?
- c++ - Similar Char(TCS CodeVita) 减少时间复杂度
- d3.js - 过滤d3时如何突出显示分组图表的一部分
- python - 在一行中的列表中添加相同值的 Pythonic 方式?
- entity-framework - 设置项目时如何更改 App.config 和数据库 (sqlite) 中的连接字符串?
- python-3.x - 在 Python 中模拟 10,000 个硬币翻转非常慢
- c# - 如何修复错误 CS1738 命名参数规范必须在指定所有固定参数后出现