Reputation: 3469
On my 2D Platformer I have Platforms that move up and down:
void FixedUpdate() {
float speed = (UnityEngine.Random.Range(1f, _speedMax));
float t = Mathf.PingPong(Time.time, speed) / speed;
transform.position = Vector2.Lerp(_start, _end, t);
}
When the player enters this moving platform, I set the platform as parent, so the player moves with it up and down.
private void OnCollisionEnter2D(Collision2D collision) {
if(collision.gameObject.tag == "Player")
collision.collider.transform.SetParent(transform);
}
On Jump I reset the parent to null:
if (jumpState == JumpState.Grounded && Input.GetButtonDown("Jump")) {
transform.SetParent(null);
jumpState = JumpState.PrepareToJump;
}
Everything works fine except for the case, that the player can't move left or right when standing in the moving platform (when the moving platform is its parent). It can jump of the platform and then keep moving.
As this behaviour only appears when the paren game object (platform) has the moving code assigned, I assume, that the moving of the player can't take place when the object is already beeing moved by the parent game object but shouldn't it be possible to move around inside parent?
The player movement is done with Rigidbody2D (complete code is in this tutorial, I did not change anything: https://learn.unity.com/tutorial/live-session-2d-platformer-character-controller):
move.x = Input.GetAxis("Horizontal");
var distance = move.magnitude;
[...]
rigidbody.position = rigidbody.position + move.normalized * distance;
Is it possible to still move inside a parent or do I have other possibilites than setting the moving platform as a parent?
Upvotes: 1
Views: 988
Reputation: 21
Thinking on it, I can suggest you to use Rigidbody.MovePosition():
Rigidbody.MovePosition(transform.position + (move.normalized * distance));
As stated in the documentation: Rigidbody.MovePosition
Rigidbody.MovePosition moves a Rigidbody and complies with the interpolation settings. When Rigidbody interpolation is enabled, Rigidbody.MovePosition creates a smooth transition between frames. Unity moves a Rigidbody in each FixedUpdate call. The position occurs in local space. Teleporting a Rigidbody from one position to another uses Rigidbody.position instead of MovePosition.
I can't try it now, let me know if it helps!
Upvotes: 1
Reputation: 1
You can instead of setting the platform as parent change the players transform.position when the platform moves:
player.tramsform.position += platformPreviosPosition - platform.transform.position;
platformPreviosPosition would be the position of the platform in the prevois frame.
But is there not a bool somewhere in the movement script that disables movement if you're on the platform, that yo uhave forgot about ?
Upvotes: 0