- Home /
Velocity in Unity2D
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.
Answer by xxmariofer · Jan 18, 2019 at 11:18 AM
you are mixing stuff, you should move the playee with rb.velocity not moving its vector and add a force with the addforce method for jumping.
Answer by mansoor090 · Jan 18, 2019 at 11:37 AM
i believe your starting velocity (initial velocity) is never greater than MaxVel. velocity.x = 0 so 0 > 3f -> which means nothing is happening since there is no else condition for it.
Plus it is not the correct way moving upward, since you are using rigidbody you can use addforce or (longer jumps work smooth on this )update transform.y using sin values
Your answer
Follow this Question
Related Questions
[Unity2D Platformer] - Why is my player Double Jumping? 4 Answers
2D Directional top down movement,Topdown 2d Directional Movement 0 Answers
How can I make an object stop all momentum and hold it's position in air? 1 Answer
[2D] Character keeps sliding when I add velocity to the rigidbody2D? 1 Answer
Movement Relative to Rotated Parent 1 Answer