我正在尝试创建棋盘游戏Hex。玩家一个在底部是黄色,而玩家二在顶部是蓝色。当Player One单击一个十六进制时,它应该变为黄色,当Player 2单击一个十六进制时,它应该变为蓝色。
我使用预制件创建了这个Hex Map,现在我希望能够在我点击它时更改每个瓷砖的颜色(你看到的黄色六角形将是透明的,但我导入的精灵是黄色的,这就是为什么颜色在Sprite渲染器上是白色的,即使六边形看起来是黄色的)。
顺便说一下,现在改变Sprite Renderer中的颜色会改变所有六边形的颜色。
我按照quill18creates的教程制作了Hex Map,除了我用2D而不是3D做的。
https://www.youtube.com/watch?v=j-rCuN7uMR8
截至撰写时,我的Color Change脚本根本不起作用。我试图这样做,当它收到一次点击它变成黄色。然后下一个单击为蓝色,下一个单击为黄色,依此类推。由于每个玩家只有一次点击。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColorChange : MonoBehaviour {
public Color[]colors; // allows input of material colors in a set sized array
public SpriteRenderer rend; // what are we rendering? the hex
private int index = 1; //initialize at 1, otherwise you have to press the ball twice to change color
// Use this for initialization
void Start () {
rend = GetComponent<SpriteRenderer> (); // gives functionality for the renderer
}
// Update is called once per frame
void onMouseDown () {
// if there are no colors present nothing happens
if (colors.Length == 0){
return;
}
if (Input.GetMouseButtonDown(0)){
index += 1; // when mouse is pressed down we increment up to the next index location
// when it reaches the end of the colors it stars over
if (index == colors.Length +1){
index = 1;
}
print (index); // used for debugging
rend.color = colors [index - 1]; // this sets the material color values inside the index
}
} //onMouseDown
}
我应该怎么做呢?任何帮助将非常感激!
首先,你需要正确地利用OnMouseDown()
来获取它。
之后,由于您使用的是SpriteRenderer
,因此您需要添加一个碰撞器来检测鼠标点击事件。如OnMouseDown()
文档中所述:
此事件将发送到Collider或GUIElement的所有脚本。
由于在预制件上没有,单击添加组件>多边形对撞机2D,它将自动为您的精灵创建正确的几何图形(假设十六进制外部的所有内容都是透明的)。
最后,删除对Input.GetMouseButtonDown(0)
的支票。 OnMouseDown已经捕获了鼠标被点击的事实,并且运行OnMouseDown()
的特定实例是被点击的实例。
在你的预制件中添加对撞机和刚体,然后在OnMouseDown中添加大写O并删除“if(Input.GetMouseButtonDown(0)){”Input.GetMouseButtonDown(0)当玩家点击任何你想要的东西时返回true
public Color[] colors; // allows input of material colors in a set sized array
public SpriteRenderer rend; // what are we rendering? the hex
private int index = 1; //initialize at 1, otherwise you have to press the ball twice to change color
// Use this for initialization
void Start()
{
rend = GetComponent<SpriteRenderer>(); // gives functionality for the renderer
}
// Update is called once per frame
void OnMouseDown()
{
// if there are no colors present nothing happens
if (colors.Length == 0)
{
return;
}
index += 1; // when mouse is pressed down we increment up to the next index location
// when it reaches the end of the colors it stars over
if (index == colors.Length + 1)
{
index = 1;
}
print(index); // used for debugging
rend.color = colors[index - 1]; // this sets the material color values inside the index
} //onMouseDown