目录
HeroColliderController.cs 控制角色与单向平台是否忽略碰撞
基于【Unity3D】实现横版2D游戏——单向平台(简易版)-CSDN博客
实现了单向平台后才能进行攀爬绳索到平台,否则攀爬到平台后会被阻挡,以及无法从平台往下攀爬。
GeneRope.cs 场景绳索生成类
GitHub - dbrizov/NaughtyAttributes: Attribute Extensions for Unity
上面是一个特性能够让脚本上出现一个按钮去点击执行我们的生成绳索方法
用法:[Button("Generate Rope")] 写在生成绳索方法头部。
绳索标签Rope
using System.Collections;
using NaughtyAttributes;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class GeneRope : MonoBehaviour
{
public Sprite top;
public Sprite middle;
public Sprite bottom;
public int ropeNodeCount;
public Vector2 ropeNodeSize;
List<GameObject> nodeList;
BoxCollider2D boxCollider2D;
[Button("Generate Rope")]
public void GenerateRope()
{
//清理
if (nodeList == null)
{
nodeList = new List<GameObject>();
}
else
{
for (int i = nodeList.Count - 1; i >= 0; i--)
{
DestroyImmediate(nodeList[i]);
}
nodeList.Clear();
}
Transform[] childrens = transform.GetComponentsInChildren<Transform>();
if (childrens != null && childrens.Length > 0)
{
for (int i = childrens.Length - 1; i >= 0; i--)
{
if (childrens[i].gameObject != this.gameObject)
{
DestroyImmediate(childrens[i].gameObject);
}
}
}
//生成绳索节点图片
for (int i = 0; i < ropeNodeCount; i++)
{
Sprite sprite;
if (i == 0)
{
//头部
sprite = top;
}
else if (i == ropeNodeCount - 1)
{
//尾部
sprite = bottom;
}
else
{
//中间
sprite = middle;
}
SpriteRenderer sp = new GameObject("node_" + i, typeof(SpriteRenderer)).GetComponent<SpriteRenderer>();
sp.sprite = sprite;
nodeList.Add(sp.gameObject);
sp.transform.SetParent(transform);
//从根节点向下延伸的绳索
sp.transform.localPosition = new Vector3(0, i * -ropeNodeSize.y - 0.5f, 0);
}
//生成绳索碰撞体(1个)
boxCollider2D = GetComponent<BoxCollider2D>();
if (boxCollider2D == null)
{
boxCollider2D = gameObject.AddComponent<BoxCollider2D>();
}
boxCollider2D.size = new Vector2(ropeNodeSize.x, ropeNodeSize.y * ropeNodeCount);
boxCollider2D.offset = new Vector2(0, boxCollider2D.size.y * -0.5f);
boxCollider2D.isTrigger = true;
//绳索标签(触发检测使用判定是否为绳索,处理攀爬逻辑)
gameObject.tag = "Rope";
}
}
HeroColliderController.cs 控制角色与单向平台是否忽略碰撞
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeroColliderController : MonoBehaviour
{
BoxCollider2D heroCollider;
public bool isOn;
Collider2D m_Collision;
public bool isIgnoreCollision = false;
private void Awake()
{
her