Hey all,
I don’ write scripts much but gave this a crack to build a moving platform in a 2D platformer. Just wondering if there is a simpler way to do this/if my script can be streamlined at all?
Basically, I’ve got a “Moving Platform” object with the following children: Platform (which has the sprites, colliders, etc), and a number of nodes (4 maximum) which are just empty objects to position around the scene. The platform heads between each node and cycles back to the first, checking how many nodes there are as it goes. At the moment, the script requires additional lines for every additional node. Not sure I’ll ever really need more than four, but wondering if there is a way to automate that element of it? Here’s my C# script:
using UnityEngine;
using System.Collections;
public class MovingPlatformScript : MonoBehaviour {
public float speed = 5f;
public float NodesHit = 1f;
//Setting up the Platform and Nodes
Transform Node1;
Transform Node2;
Transform Node3;
Transform Node4;
Transform Platform;
void Awake () {
//Find the Platform and Nodes children
Node1 = transform.Find("Node1");
Node2 = transform.Find("Node2");
Node3 = transform.Find("Node3");
Node4 = transform.Find("Node4");
Platform = transform.Find("Platform");
}
void FixedUpdate () {
//Control the movement of the Platform between nodes
if (NodesHit == 1f) {
Platform.position = Vector2.MoveTowards (Platform.position, Node2.position, speed * Time.deltaTime);
}
if (NodesHit == 2f) {
if (Node3 != null) {
Platform.position = Vector2.MoveTowards (Platform.position, Node3.position, speed * Time.deltaTime);
}
else {
Platform.position = Vector2.MoveTowards (Platform.position, Node1.position, speed * Time.deltaTime);
}
}
if (NodesHit == 3f) {
if (Node4 != null) {
Platform.position = Vector2.MoveTowards (Platform.position, Node4.position, speed * Time.deltaTime);
} else {
Platform.position = Vector2.MoveTowards (Platform.position, Node1.position, speed * Time.deltaTime);
}
}
if (NodesHit == 4f) {
Platform.position = Vector2.MoveTowards (Platform.position, Node1.position, speed * Time.deltaTime);
}
//Keep track of the nodes that have been hit
float Node1Check = Vector2.Distance (Platform.position, Node1.position);
if (Node1Check <= 1) {
NodesHit = 1f;
}
float Node2Check = Vector2.Distance (Platform.position, Node2.position);
if (Node2Check <= 1) {
NodesHit = 2f;
}
//Check for additional nodes and continue to count if they exist, otherwise head back to the first node
if (Node3 != null) {
float Node3Check = Vector2.Distance (Platform.position, Node3.position);
if (Node3Check <= 1) {
NodesHit = 3f;
}
}
if (Node4 != null) {
float Node4Check = Vector2.Distance (Platform.position, Node4.position);
if (Node4Check <= 1) {
NodesHit = 4f;
}
}
}
}