我正在做一个化学分子游戏。到目前为止,我有一个在受体位点上带有触发器的分子,当我将正确的原子拖到该位点附近时,原子会改变颜色并附着。一旦这个原子附着,我如何改变整个分子(不仅仅是触发/受体位点)的颜色?
用于我游戏这部分的代码来自: https://gamedev.stackexchange.com/questions/123929/snap-an-object-to-another-object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Snap : MonoBehaviour
{
public string partnerTag;
public float closeVPDist = 0.05f;
public float farVPDist = 1;
public float moveSpeed = 40.0f;
public float rotateSpeed = 90.0f;
private Vector3 screenPoint;
private Vector3 offset;
private bool isSnaped;
Color color = new Color(2, 1, 3);
float dist = Mathf.Infinity;
Color normalColor;
GameObject partnerGO;
// Use this for initialization
void Start()
{
normalColor = GetComponent<Renderer>().material.color;
partnerGO = GameObject.FindGameObjectWithTag(partnerTag);
}
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(transform.position);
offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
Cursor.visible = false;
}
void OnMouseDrag()
{
//transform.SetParent(null);
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
Vector3 partnerPos = Camera.main.WorldToViewportPoint(partnerGO.transform.position);
Vector3 myPos = Camera.main.WorldToViewportPoint(transform.position);
dist = Vector2.Distance(partnerPos, myPos);
GetComponent<Renderer>().material.color = (dist < closeVPDist) ? color : normalColor;
}
void OnMouseUp()
{
Cursor.visible = true;
if (dist < closeVPDist)
{
transform.SetParent(partnerGO.transform);
StartCoroutine(InstallPart());
isSnaped = true;
}
if (dist > farVPDist)
{
// transform.SetParent(null);
}
}
IEnumerator InstallPart()
{
while (transform.localPosition != Vector3.right || transform.localRotation != Quaternion.identity)
{
transform.localPosition = Vector3.MoveTowards(transform.localPosition, Vector3.right, Time.deltaTime * moveSpeed);
transform.localRotation = Quaternion.RotateTowards(transform.localRotation, Quaternion.identity, Time.deltaTime * rotateSpeed);
yield return new WaitForEndOfFrame();
}
}
}
在OnMouseUp
中,添加一条线来改变分子的材料/颜色。法典:
public Color newColor;
public GameObject objectToChangeColour;
void OnMouseUp()
{
Cursor.visible = true;
if (dist < closeVPDist)
{
transform.SetParent(partnerGO.transform);
StartCoroutine(InstallPart());
isSnaped = true;
objectToChangeColour.GetComponent<Renderer>().material.color = newColour; // Change the color of object to the newColour
}
if (dist > farVPDist)
{
// transform.SetParent(null);
}
}
只需将objectToChangeColour
更改为要更改其颜色的对象(parentGO/分子/等),newColour
更改为新颜色。