属性
简介 | 方法 |
注意:准星一般都放在屏幕正中央,所以屏幕的(宽高/2)可得中心点 | |
屏幕宽度 | Screen.Width |
屏幕高度 | Screen.Height |
矩形宽度 | 自己声明的变量这里使用W代替 |
矩形高度 | 自己声明的变量这里使用H代替 |
准星间距 | 自己声明的变量这里使用D代替 |
解释图
写入过程
因为我们想要动态准星所以打算自己用代码写一个,而不用图片直接贴上去
- 先声明准星的宽高,和间距其次就是准星贴图了
- 再声明两个变量GUIStyle(用来自定义设置GUI参数)和Texture(准星背景辅助参数,也可以理解为凑数的)
- 在游戏刚开始的时候将GUIStyle实例化并且将准星贴图赋值给其中的normal.background属性
- 使用GUI.Box方法在屏幕中心绘制四个矩形绘制成一个准星
- Box(Rect,Image,GUIStyle)(Unity文档中GUIStyle简介)
- 这里的Rect表示创建一个矩形框架(坐标x,坐标y,矩形宽度,矩形高度)
- Image(在这个方法中并没有实质性的作用,但是想要使用这个方法必须要填入Image,所以创建一个但不赋值起到凑数作用)
- GUIStyle(我们准星的设置是在这个参数里,如果不给这个参数赋值的话使用的将会是Unity自带的GuiStyle设置)
- 在这里我就声明静态准星了,动态的话在某个动作的时候改变坐标、间距和宽高就行了
实例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FPS_CrossHair : MonoBehaviour
{
[Header("准星的长度")]
public float width;
[Header("准星的高度")]
public float height;
[Header("上下(左右)两条准星之间的距离")]
public float distance;
[Header("准星背景图")]
public Texture2D crosshairTexture;
private GUIStyle lineStyle; // GUI自定义参数
private Texture tex; // 准星背景辅助参数
private void Start()
{
lineStyle = new GUIStyle(); // 游戏开始实例化背景图
lineStyle.normal.background = crosshairTexture; // 将背景图默认背景设为准星背景
}
private void OnGUI()
{
// 左准星
GUI.Box(new Rect(Screen.width / 2 - distance / 2 - width, Screen.height / 2 - height / 2, width, height), tex, lineStyle);
// 右准星
GUI.Box(new Rect(Screen.width / 2 + distance / 2 , Screen.height / 2 - height / 2, width, height), tex, lineStyle);
// 上准星
GUI.Box(new Rect(Screen.width / 2 - height / 2, Screen.height / 2 - distance / 2 - width, height, width), tex, lineStyle);
// 下准星
GUI.Box(new Rect(Screen.width / 2 - height / 2, Screen.height / 2 + distance / 2, height, width), tex,lineStyle);
}
}