I’ve made a script for left/right movement and jumping in 2D:
using UnityEngine;
public class char1Move : MonoBehaviour
{
public Rigidbody2D rb;
void Update()
{
float Dirx = Input.GetAxis("Horizontal");
float Diry = 0.2f;
if (Input.GetKey(KeyCode.UpArrow))
{
transform.position = new Vector2(transform.position.x + Dirx, transform.position.y + Diry);
}
transform.position = new Vector2(transform.position.x + Dirx, transform.position.y);
}
}
This is working, but when I add in anything related to velocity, the script doesn’t work anymore:
using UnityEngine;
public class char1Move : MonoBehaviour
{
public Rigidbody2D rb;
// Update is called once per frame
void Update()
{
float Dirx = Input.GetAxis("Horizontal");
float Diry = 0.2f;
float maxVel = 3f;
if (Input.GetKey(KeyCode.UpArrow))
{
transform.position = new Vector2(transform.position.x + Dirx, transform.position.y + Diry);
}
transform.position = new Vector2(transform.position.x + Dirx, transform.position.y);
if (rb.velocity.x > maxVel)
{
rb.velocity = new Vector2(maxVel, rb.velocity.y);
}
}
}
Does anyone know why?
P.S. How do I make a point on the y-axis beyond which a player cannot jump? I don’t want my character to escape the laws of physics.