第三章:角色控制
本篇博客主要对人物移动及其相关操作进行分析,主要包括主角以及镜头的移动。
在游戏界面中,我们使用Camera作为视角。为了方便之后判断当前tag,我们新建一个Tag脚本,存入一些tag信息,之后调用就不容易出错
using UnityEngine;
using System.Collections;
public class Tags : MonoBehaviour {
public const string ground = "Ground";
public const string player = "Player"; //新建角色与地面的tag信息,之后还会添加物品等信息
}
3.1 点击地板
Map中的Terrain可以判断鼠标是否点击到地面,因此我们向Map中拖入一个Magician,为它添加一个脚本PlayerDirection,实现点击地板产生效果的功能。代码如下
using UnityEngine;
using System.Collections;
public class PlayerDirection : MonoBehaviour {
public GameObject effect_click_prefab;
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown (0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //创建一个射线,将在Camera中点击的点转化为一条射线
RaycastHit hitInfo; //创建碰撞信息
bool isCollider = Physics.Raycast(ray,out hitInfo); //isCollider检测是否碰撞,其中Physics.Raycast中的两个形参表示射线以及碰撞信息
if(isCollider && hitInfo.collider.tag == Tags.ground) //发生碰撞且碰撞的物体其Tag为ground
{
showClickEffect(hitInfo.point); //实例化点击效果
}
}
}
void showClickEffect(Vector3 hitPoint)
{
hitPoint = new Vector3 (hitPoint.x, hitPoint.y + 0.1f, hitPoint.z); //将碰撞点的y向上移动一些,以完整显示
GameObject.Instantiate (effect_click_prefab, hitPoint, Quaternion.identity); //创建一个实例,显示点击信息
}
}
即可
之后将点击效果导入,即可实现