Unity 对Transform扩展, 限制方盒形移动区域

↓在不会扩展前我是这么写的:

    /// /// 限制Vector3区域在一个方形区域/// public static Vector3 Clamp(Vector3 pos, Vector3 min, Vector3 max){float x = Mathf.Clamp(pos.x, min.x, max.x);float y = Mathf.Clamp(pos.y, min.y, max.y);float z = Mathf.Clamp(pos.z, min.z, max.z);Vector3 result = new Vector3(x, y, z);return result;}

后来我学了扩展,
有一种恍然大悟的感觉! 原来可以这样写! 就特别爽

    /// /// Transform的扩展方法, 限制区域/// public static void ClampPos(this Transform trs, Vector3 min, Vector3 max){float x = Mathf.Clamp(trs.position.x, min.x, max.x);float y = Mathf.Clamp(trs.position.y, min.y, max.y);float z = Mathf.Clamp(trs.position.z, min.z, max.z);trs.position = new Vector3(x, y, z);}

就能直接用了

transform.ClampPos(Vector3.zero, Vector3.one);

其实就是个静态方法, 不同是, 要在参数前写上 this Transform trs,

注意: 扩展方法要放在静态类里 !!!
能实例化的类型才能被扩展, 比如Resources类就不能被扩展


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部