本文介绍了拍摄到屏幕中央的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码用于直接发射激光.
This code is used to fire laser straight forward.
using UnityEngine;
using System.Collections;
public class LeftGun : MonoBehaviour {
public Rigidbody laser;
public AudioClip LaserShot;
float shotSpeed = 0.1f;
bool canShoot = true;
// Update is called once per frame
void Update () {
if(!Engine.escape)
{
shotSpeed -= Time.deltaTime;
if(shotSpeed <= 0f)
canShoot = true;
if(Input.GetButton("Fire1") && canShoot)
{
shotSpeed = 0.1f;
canShoot = false;
PlayerGUI.ammunition--;
audio.PlayOneShot(LaserShot);
Rigidbody clone = Instantiate(laser,transform.position, transform.rotation) as Rigidbody;
clone.velocity = transform.TransformDirection(-80, 0, 0);
Destroy(clone.gameObject, 3);
}
}
}
我想向屏幕中央(十字线所在的位置)开火.我要怎么做到呢?
图片示例: http://i.imgur.com/EsVsQNd.png
I would like to fire to the center of the screen (where crosshair is). How can I achive that?
Example image: http://i.imgur.com/EsVsQNd.png
推荐答案
您可以使用相机.ScreenPointToRay .要从主相机的中心获取光线,请使用:
You can use Camera.ScreenPointToRay. To get the ray from center of the main camera, use:
float x = Screen.width / 2f;
float y = Screen.height / 2f;
var ray = Camera.main.ScreenPointToRay(new Vector3(x, y, 0));
clone.velocity = ray.direction * laserSpeed;
laserSpeed是一个公共浮标,它是您希望激光以其行进的速度.您可以根据需要进行更改(对于您提供的代码,laserSpeed为80).
laserSpeed is a public float which is the speed with which you want the laser to travel at. You can change it according to your needs (for the code you provided, laserSpeed would be 80).
这篇关于拍摄到屏幕中央的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!