moving platform
unknown
csharp
a year ago
2.0 kB
3
Indexable
using System.Collections; using System.Collections.Generic; using System.Net; using UnityEngine; public class MovingPlatform : MonoBehaviour { public Transform posA, posB; public Transform platform; public float speed; Vector3 targetPos; public PlayerMovement playerMovement; Rigidbody2D rb; Vector3 moveDirection; private void Awake() { playerMovement = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerMovement>(); rb = GetComponent<Rigidbody2D>(); } private void OnDrawGizmos() { if (platform != null && posB != null && posA != null) { Gizmos.DrawLine(platform.transform.position, posB.position); Gizmos.DrawLine(platform.transform.position, posA.position); } } private void Start() { targetPos = posB.position; DirectionCalculate(); } private void Update() { if (Vector2.Distance(transform.position, posA.position) < 0.05f) { targetPos = posB.position; DirectionCalculate(); } if (Vector2.Distance(transform.position, posB.position) < 0.05f) { targetPos = posA.position; DirectionCalculate(); } //transform.position = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime); } private void FixedUpdate() { rb.velocity = moveDirection * speed; } void DirectionCalculate() { moveDirection = (targetPos - transform.position).normalized; } private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player")) { playerMovement.platformRb = rb; playerMovement.isOnPlatform = true; } } private void OnTriggerExit2D(Collider2D collision) { if (collision.CompareTag("Player")) { collision.transform.parent = null; playerMovement.isOnPlatform = false; } } }
Editor is loading...
Leave a Comment