I’m using rigidbody2D.velocity to move my character around based on keyboard input. Is there a way to modify the distance portion of the velocity when the character jumps? Right now, the character jumps way too far. I’m currently using addforce, but that doesn’t seem to get me what I want. I pretty much want to half the distance while keeping the time the same.
EDIT: Here’s my current code for the character controller:
using UnityEngine;
using System.Collections;
public class AvaController : MonoBehaviour
{
public float maxSpeed = 5f;
private bool facingRight = true;
Animator anim;
bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
private float move;
public bool jumping = false;
public Vector2 jumpForce = new Vector2(120f, 330f);
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
print (rigidbody2D.velocity.x);
print (jumping);
// Allow jump in FixedUpdate
JumpUpdate();
// Play crouching animation
if( grounded && Input.GetKey(KeyCode.S) )
{
anim.SetBool("Crouching", true);
}
else
{
anim.SetBool("Crouching", false);
}
}
void FixedUpdate()
{
// Check to see if the player is touching a "ground"
grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
anim.SetBool("Ground", grounded);
Jump();
// If player is not on the ground, player cannot control the character
if (!grounded)
return;
if (anim.GetBool("Crouching") == false)
{
move = Input.GetAxis("Horizontal");
anim.SetFloat("speed", Mathf.Abs(move));
rigidbody2D.velocity = new Vector2(move * maxSpeed, rigidbody2D.velocity.y);
}
if( (move > 0) && (!facingRight) )
Flip();
else if( (move < 0) && (facingRight) )
Flip();
}
void JumpUpdate()
{
if (!jumping) {
if( (anim.GetBool("Crouching") == false) && grounded && Input.GetKeyDown(KeyCode.Space) )
{
jumping = true;
}
}
}
void Jump()
{
if(jumping)
{
rigidbody2D.AddForce(new Vector2(0f, jumpForce.y));
anim.SetFloat("vSpeed", rigidbody2D.velocity.y);
anim.SetBool("Ground", false);
if(rigidbody2D.velocity.x != 0)
{
rigidbody2D.AddForce(new Vector2(-5.8f, 0f));
print (rigidbody2D.velocity.x);
}
else
{
rigidbody2D.velocity = new Vector2(0,rigidbody2D.velocity.y);
}
if(rigidbody2D.velocity.y == 0)
jumping = false;
}
}
void Flip()
{
facingRight = !facingRight;
Vector3 avaScale = transform.localScale;
avaScale.x *= -1;
transform.localScale = avaScale;
}
}
This works perfectly if I comment out the rigidbody2d velocity in my horizontal movement code, but then they character can’t move left or right.