Quantcast
Channel: GameDev.net
Viewing all articles
Browse latest Browse all 17825

Moving platform (2D UNITY)

$
0
0
Hey I'm trying to make a moving platform in 2D unity engine using C#. I actually learned this in a video but can't do it myself. So that's what i did : I wrote two codes: 1.Followpath.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class FollowPath : MonoBehaviour { public enum FollowType { MoveTowards, Lerp } public FollowType Type = FollowType.MoveTowards; public PathDefinition Path; public float Speed = 1; public float MaxDistanceToGoal = .1f; private IEnumerator<Transform> _currentPoint; public void Start() { if (Path == null) { Debug.LogError("Path cannot be null", gameObject); return; } _currentPoint = Path.GetPathEnumerator(); _currentPoint.MoveNext(); if (_currentPoint.Current == null) return; transform.position = _currentPoint.Current.position; } public void update() { if (_currentPoint == null || _currentPoint.Current == null) return; if (Type == FollowType.MoveTowards) transform.position = Vector3.MoveTowards(transform.position, _currentPoint.Current.position, Time.deltaTime * Speed); else if (Type == FollowType.Lerp) transform.position = Vector3.Lerp(transform.position, _currentPoint.Current.position, Time.deltaTime * Speed); var distanceSquared = (transform.position - _currentPoint.Current.position).sqrMagnitude; if (distanceSquared < MaxDistanceToGoal * MaxDistanceToGoal) _currentPoint.MoveNext(); } } 2.PathDefiniton.cs using System; using System.Collections.Generic; using UnityEngine; using System.Collections; public class PathDefinition : MonoBehaviour { public Transform[] Points; public IEnumerator<Transform> GetPathEnumerator() { if (Points == null || Points.Length < 1) yield break; var direction = 1; var index = 0; while (true) { yield return Points[index]; if (Points.Length == 1) continue; if (index <= 0) direction = 1; else if (index >= Points.Length - 1) direction = -1; index = index + direction; } } public void OnDrawGizmos() { if (Points == null || Points.Length < 2) return; for (var i = 1; i < Points.Length; i++) { Gizmos.DrawLine(Points[i - 1].position, Points[i].position); } } } and made a gameobject "platform path" and added PathDefiniton.cs to it then made 3 new gameobjects "start" "mid" and "end" as spots in path and set them as 3 elements to "platform path" so I made another object( a sprite like a dirt to follow path) "Platform" and added "Followpath.cs" to it: Finally: when i start the game, platform will move to "start" spot but doesn't follow "mid" and "end". Can anyone help me please? I'll change it to a guide if i fix it. or if you have no idea, give me a new way to make a moving platform.

Viewing all articles
Browse latest Browse all 17825

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>