My game is a magnet maze, where you attach a magnet from underneath to a cube on top. It just needs to be below it to be able to able. There's an indicator set up to show when a cube is above the magnet but I don't yet have the code that enables the magnet to move the cube around wherever it moves.
This is my current code for the magnet:
using UnityEngine;
using System.Collections;
public class Magnet : MonoBehaviour {
public GameObject indicator;
public Color attachableColour;
public Color detachedColour;
public CubeManager cubeManager;
public GameObject magnetisedCube;
public bool attaching;
public bool attachable;
public float attachRadius;
private float distToCube;
private GameObject closestCube;
private float distToClosestCube;
private Vector2 magPos;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if (attaching)
{
magPos = new Vector2(transform.position.x, transform.position.z);
foreach(GameObject cube in cubeManager.cubes)
{
Vector2 cubePos = new Vector2(cube.transform.position.x, cube.transform.position.z);
distToCube = Vector2.Distance(magPos, cubePos);
if (distToCube <= attachRadius)
{
if (closestCube == null)
{
distToClosestCube = distToCube;
closestCube = cube;
}
else if (distToCube < distToClosestCube)
{
distToClosestCube = distToCube;
closestCube = cube;
}
}
}
if (closestCube != null)
{
attaching = false;
magnetisedCube = closestCube;
}
}
else
{
attachable = false;
magPos = new Vector2(transform.position.x, transform.position.z);
foreach(GameObject cube in cubeManager.cubes)
{
Vector2 cubePos = new Vector2(cube.transform.position.x, cube.transform.position.z);
distToCube = Vector2.Distance(magPos, cubePos);
if (distToCube <= attachRadius)
{
attachable = true;
break;
}
}
if (attachable == false)
{
indicator.renderer.material.color = detachedColour;
}
else
{
indicator.renderer.material.color = attachableColour;
}
}
if (attachable)
{
if(Input.GetMouseButtonDown(0))
{
attaching = true;
}
}
else
{
magnetisedCube = null;
}
}
}
If someone can tell me what I need to add to this then I'd be very grateful.
↧