我正在Unity中创建一个2D头顶游戏。到目前为止,我已经能够让玩家以接近正确的角度跟随鼠标(但它仍然以奇怪的方式移动)。我也试图给玩家一个拍摄功能,从正确的角度拍摄一条光线(直接从拍摄时的播放器顶部)。当我点击使用此代码时,没有任何反应。我为玩家,子弹和火点设置了对象。
public void Update()
{
if (FollowMouse || Input.GetMouseButton(0))
{
_target = Camera.ScreenToWorldPoint(Input.mousePosition);
_target.z = 0;
}
var delta = currentSpeed * Time.deltaTime;
if (ShipAccelerates)
{
delta *= Vector3.Distance(transform.position, _target);
}
angle = Mathf.Atan2(_target.y, _target.x) * Mathf.Rad2Deg;
transform.position = Vector3.MoveTowards(transform.position, _target, delta);
transform.rotation = Quaternion.Euler(0, 0, angle);
if ((Input.GetMouseButtonDown(0) || Input.GetKeyDown("space")) && Time.time > nextFire && numOfBullets > 0)
{
nextFire = Time.time + fireRate;
// Instantiate(bullet, firePoint.position, firePoint.rotation);
numOfBullets--;
// bullet.transform.position = Vector3.MoveTowards(bullet.transform.position, _target, bulletDelta);
shoot();
firePoint.position = _target;
}
if(Input.GetMouseButtonDown(1) && fuel > 0)
{
currentSpeed = zoomSpeed;
while(fuel > 0)
{
fuel--;
}
currentSpeed = ShipSpeed;
}
}
void Start()
{
currentSpeed = ShipSpeed;
}
void shoot()
{
Vector2 mousePosition = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
Vector2 firePointPosition = new Vector2(firePoint.position.x, firePoint.position.y);
RaycastHit2D hit = Physics2D.Raycast(firePointPosition, mousePosition-firePointPosition, 100, notToHit);
Debug.DrawLine(firePointPosition, _target);
}
试试这个,它将从gameobject的位置开始射击,然后沿着transform.right的方向走100,并忽略“notToHit”。 debug.drawRay将在场景视图中显示一条红线,显示光线(距离为1)。在你完成所有工作后删除它,因为它会减慢你的游戏速度。
RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position,transform.right,100, notToHit);
if (hit.transform != null) {
Debug.Log ("You Hit: "hit.transform.gameObject.name);
}
Debug.DrawRay (gameObject.transform.position, transform.right, Color.red, 5);
我使用transform.right而不是将角度计算到鼠标位置的共振是因为你说玩家跟随鼠标(所以我假设玩家已经在看鼠标了)。但是,如果这不是您想要的,您可以随时将其更改为您想要的。