Im making a top down game in unity. in my game there is a platform where the player can stand on. while this platform is moving the player moves with it. here is an example:
This almost works like i want it to. The player moves together with the platform and is still able to move while on it. (note that currently the player will always follow the platform. there is no check to see if the player is on the platform or not. but that's done for testing.). What i want know is that when the platform rotates the player will also follow the rotation. currently it looks like this when the platform is rotating:
here i move my character to show what i want to achieve:
This is the code for moving my player and also the code that keeps me on the platform:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
public Rigidbody2D platform;
public Camera cam;
Vector2 movement;
Vector2 mousePos;
// Update is called once per frame
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
Vector2 pos;
private void FixedUpdate()
{
pos = pos + movement;
rb.MovePosition(platform.position + pos * moveSpeed * Time.fixedDeltaTime);
Vector2 lookDir = mousePos - rb.position;
float angle = Mathf.Atan2(lookDir.y,lookDir.x) * Mathf.Rad2Deg - 90f;
rb.rotation = angle;
}
}
this is the code for moving the platform:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Platform : MonoBehaviour
{
public float moveSpeed = 5f;
public Rigidbody2D rb;
public Vector2 movement;
private void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
rb.MovePosition(rb.position + new Vector2(1f, 0) * Time.fixedDeltaTime);
rb.MoveRotation(rb.rotation + 25f * Time.fixedDeltaTime);
}
}
I know that is also possible to make the player a child of the platform and then move the platform by updating the transformation position. but i choose for a rigidbody for the platform movement because I want the player to be able to control the platform later on and then i will use things like addforce.