塔防类游戏 简单的角色合并逻辑示例,主要使用射线检测完成
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MergeByRayCast : MonoBehaviour
{
public Platform platform;
private bool isClick = true;
private RaycastHit hit;
private void OnMouseDown()
{
isClick = false;
}
//拖动时角色跟随鼠标位置移动
private void OnMouseDrag()
{
if (!isClick)
{
Ray _ray = Camera.main.ScreenPointToRay(Input.mousePosition);
bool hasHit = Physics.Raycast(_ray.origin, _ray.direction, out hit, 10000, 1 << PhysicsLayer.PLANE);
if (hasHit)
{
Debug.Log(hit.transform.gameObject.name + "----" + hit.transform.gameObject.layer);
transform.position = hit.point;
}
}
}
//鼠标抬起时检测当前鼠标是否点在炮台上,如果是进行合并或者替换,如果不是该角色就返回原来的炮台上
private void OnMouseUp()
{
if (!isClick)
{
Ray _ray = Camera.main.ScreenPointToRay(Input.mousePosition);
bool hasHit = Physics.Raycast(_ray.origin, _ray.direction, out hit, 10000, 1 << PhysicsLayer.PLATFORM | 1 << PhysicsLayer.PLANE);
if (hasHit)
{
Debug.Log(hit.transform.gameObject.name + "---" + hit.transform.gameObject.layer);
if (hit.transform.gameObject.layer == PhysicsLayer.PLATFORM)
{
Platform _platform = hit.collider.gameObject.GetComponent<Platform>();
MergeByRayCast _hero = _platform.hero;
if (_hero != null)
{
if(_platform.hero != this)
{
_platform.hero = this;
platform.hero = null;
platform = _platform;
_hero.platform = null;
_hero.gameObject.SetActive(false);
}
}
else
{
platform.hero = null;
_platform.hero = this;
platform = _platform;
transform.position = _platform.transform.position;
}
}
}
transform.position = platform.transform.position;
isClick = true;
}
}
}
public class PhysicsLayer
{
public const int PLANE = 8;
public const int HERO = 9;
public const int PLATFORM = 10;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//非常简单的炮台类
public class Platform : MonoBehaviour
{
public MergeByRayCast hero;
// Start is called before the first frame update
void Start()
{
hero.gameObject.transform.position = transform.position;
}
}