I am making my first game in Unity and I really enjoy it, but I have run into a very annoying problem. My game is a platform game where the character is always running right. My character has a rigidbody2D component attached to it. I am now trying to implement platforms moving up and down and I am using this script:
void Update()
{
transform.position = Vector2.MoveTowards (transform.position, patrolPoints [pointToReach].position,moveSpeed * Time.deltaTime);
if (transform.position == patrolPoints [pointToReach].position)
{
if (pointToReach == patrolPoints.Length - 1)
{
pointToReach = 0;
}
else
{
pointToReach++;
}
}
}
I move the character by changing the velocity of the Rigidbody2D component. That is done with the code:
void FixedUpdate ()
{
if (alive && !levelWon)
{
if (playerBody.velocity.x <= 0 && !onGround)
{
playerBody.velocity = new Vector2 (playerBody.velocity.x, playerBody.velocity.y);
}
else
{
playerBody.velocity = new Vector2 (moveSpeed, playerBody.velocity.y);
}
}
}
It works beautifully but my problem is when my character lands on the moving platform, he is not moving smoothly with the platform because he is not attached to it. I came across a solution that I really like that involves making the character a child of the platform as long as it is on it so I used that:
void OnCollisionEnter2D(Collision2D target)
{
if (target.gameObject.tag == "MovingPlatform")
{
transform.parent = target.gameObject.transform;
}
}
void OnCollisionExit2D(Collision2D target)
{
if (target.gameObject.tag == "MovingPlatform")
{
transform.parent = null;
}
}
It works when I use the Interpolate setting None but the movement of my character is not smooth with this setting. I have been using interpolation with very smooth movement but it does not work with the moving platform. As soon as it lands on the platform and becomes a child of the platform it moves much more slowly than before, with extrapolation the problem is the opposite, he speeds up.
I hope I have made my problem clear, any thoughts or help is much appreciated
Thanks in advance - The confused game developer
↧