- Home /
Can't implement jumping to 2D side-scroller click-to-move.
So I'm trying to make a 2d side-scroller platformer, but instead of using traditional "Left/Right" arrow keys or "A/D", I've created a click to move controller that only moves the player horizontally. However I'm trying to implement a jump mechanic but I cannot seem to get the jump to work right with the click to move controls. Whenever I jump the character seems to have a varied jump velocity every time. Also when I walk off of platforms (to get to another platform below) the character seems to stop midair for a second then actually start to fall and I also think it is because of how my click to move controller is set up. Any suggestions/tips would be greatly appreciated! Here is my movement code:
public Rigidbody2D rb;
public float speed = 10f;
private Vector2 targetPosition;
private bool isMoving = false;
//grounded check for jumps
public float jumpVelocity = 10f;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
private void Update()
{
if (Input.GetMouseButton(0))
{
SetTargetPosition();
}
if (Input.GetKey(KeyCode.LeftShift))
{
isMoving = false;
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
{
rb.velocity = Vector2.up * jumpVelocity * Time.deltaTime;
}
if (transform.position.y == targetPosition.y && transform.position.x == targetPosition.x)
{
isMoving = false;
}
}
private void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
if (isMoving)
{
rb.position = Vector3.MoveTowards(rb.position, targetPosition, speed * Time.deltaTime);
}
}
private void SetTargetPosition()
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPosition.y = transform.position.y;
isMoving = true;
}
Answer by PastorJason · Sep 22, 2020 at 07:13 AM
So I figured out the problem with my code. Basically I was moving my rigidbody on both the x and y axis therefore my jump was being run over by the click to move mechanic. So I changed my rigid body to only move on a new Vector2 that was the x value of the click to move and the y value of my current position. All in all I changed line 31 to:
if (rb.position.x == targetPosition.x)
and line 42 to:
rb.position = Vector2.MoveTowards(rb.position, new Vector2(targetPosition.x, rb.position.y), speed*Time.deltaTime);
Your answer
Follow this Question
Related Questions
Long press for charged Jump 1 Answer
Raycast2D not working 1 Answer
Problem with Jump 1 Answer
How do I do a Snappy Jump in 2D with a 2D Jump Script? 0 Answers