veloity And collider HELP !!!!!!!!!!!!!! NOOB

my problem is that my sprite doesnt work

i have a button and when i press the button it moves the sprite in a certain direction until the button is released it stops

but when the gravity is on and the sprite collides with the floor and i press the button he moves and slows to a stop

i mad a new project just to test but same result the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class moveSphere : MonoBehaviour {

Rigidbody2D rb;
public int movespeed;

// Use this for initialization
void Start ()
{
rb = GetComponent();
}

// Update is called once per frame
void Update ()
{

}

public void rightButtonDown()
{
rb.velocity = new Vector2(movespeed * Time.deltaTime , 0);
}

public void buttonsUp()
{
rb.velocity = Vector2.zero;
}

}

Hi,

best to use code tags in future posts:

OK, in your code you set the velocity only on keydown, so then if the rigidbody experiences friction it will slow to a stop.

If you want to ensure constant velocity per frame (when key pressed) then something like below should do it.

No need to scale by Time.deltaTime in this case, physics engine will do that. But if you were translating (without physics) in update then yes… scale by deltaTime.

Update gets called once per frame, but to ensure smooth move you should use FixedUpdate; that gets called once per physics engine iteration.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class moveSphere : MonoBehaviour
{

    Rigidbody2D rb;
    public int movespeed;
    private Vector2 vVelocity = Vector2.zero;

    // Use this for initialization
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    // Update is called once per physics frame
    void FixedUpdate()
    {
        if(rb)
        {
            rb.velocity = vVelocity;
        }
    }

    public void rightButtonDown()
    {
        vVelocity.x = movespeed;
    }

    public void buttonsUp()
    {
        vVelocity.x = 0;
    }

}
2 Likes

thanks i have fixed it i realised that the new vector for the velocity in the why access was 0 for some reason it messed with the gravity no ideawhy but ive got this now
if (Input.GetKey(KeyCode.RightArrow))
{
rb.velocity = new Vector2(runspeed * Time.deltaTime, rb.velocity.y);
anime.SetInteger(“MoveCode”, 1);
}
else
{
rb.velocity = new Vector2(0, rb.velocity.y);
}

best to use code tags in future posts: