用NGUI实现刮刮乐的效果

用NGUI实现刮刮乐的效果
需要设置纹理是可读写的。

using UnityEngine;

[RequireComponent(typeof(UITexture))]
public class ChangeTexturePixel : MonoBehaviour {
	private UITexture mUITex;
	private Texture2D MyTex;
	public int Radius = 10;
	public Color Col = new Color(0,0,0,0);
	void Awake()
	{
		mUITex = GetComponent<UITexture>();
		var tex = mUITex.mainTexture as Texture2D;
		MyTex = new Texture2D(tex.width, tex.height, tex.format, false);
		MyTex.SetPixels(tex.GetPixels());
		MyTex.Apply();
		mUITex.mainTexture = MyTex;
	}
	
	void ChangePixelColorByCircle(int x, int y, int radius, Color col)
	{
		for (int i = -Radius; i < Radius; i++)
		{
			var py = y + i;
			if (py < 0 || py >= MyTex.height)
			{
				continue;
			}
			
			for (int j = -Radius; j < Radius; j++)
			{
				var px = x + j;
				if (px < 0 || px >= MyTex.width)
				{
					continue;
				}
				if (new Vector2(px - x, py - y).magnitude > Radius)
				{
					continue;
				}
				MyTex.SetPixel(px, py, Col);
			}
		}
		MyTex.Apply();
	}
	
	int[] WorldPos2Pix(Vector3 worldPos)
	{
		var temp = transform.InverseTransformPoint(worldPos);
		var pos = new Vector2(temp.x+mUITex.width/2,temp.y+mUITex.height/2);
		float rateX = mUITex.width / (float)MyTex.width;
		float rateY = mUITex.height / (float)MyTex.height;
		
		return new []
		{
			(int)(pos.x / rateX), (int)(pos.y/rateY)
		};
		
	}
	
	void Update ()
	{
		if (Input.GetMouseButton(0))
		{
			Vector3 worldPos = UICamera.currentCamera.ScreenToWorldPoint(Input.mousePosition);
			var posA = WorldPos2Pix(worldPos);
			ChangePixelColorByCircle(posA[0], posA[1], Radius, Col);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nmg10

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值