I have a scene that looks like the following picture:
The Player
has a RigidBody2D
and all the step
s have a BoxCollider2D
. All steps are tagged with a 'step' tag
.
I would like to let the player move to the next step
, every time the user presses a key
. In this case, I'll need to get the position
of the next step
that is the closest to the player, every time the player moves to the next position.
I have tried the following so far:
using UnityEngine;
using System.Linq;
public class Box : MonoBehaviour
{
//the rigidbody of the box
private Rigidbody2D player2D;
// Start is called before the first frame update
void Start()
{
player2D = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Vector2 targetPosition = GetNextTargetTransform(player2D.position );
//here set trajectory to move from current position to target position
Vector2 trajectory = SetTrajectory(player2D, targetPosition);
player2D.AddForce(trajectory, ForceMode2D.Impulse);
//after reach the position update player position to current position
//player2D.position = targetPosition;
}
}
public Vector2 GetNextTargetTransform(Vector2 player2Dposition)
{
GameObject[] step = GameObject.FindGameObjectsWithTag("step");
//here is the code to get the nearest object using LinQ
var nearest = step.OrderBy(t => Vector2.Distance(player2Dposition, t.transform.position)).FirstOrDefault();
Transform nearestPosition = nearest.transform;
Vector2 targetPosition = new Vector2(nearestPosition.position.x, nearestPosition.position.y);
return targetPosition;
}
}
I am able to get the position of the first step when a button is pressed, but when I press the key again, I am unable to get the position of the next step (and thus remain on the first position).
I've added player2D.position = targetPosition;
after AddForce(...)
and the player will directly appear on the first step and move to the next one, which is not the result I want.
Question
How do I get the position of the nearest step
, every time the player moves to a new step?