THIS WAS SOLVED THANKS TO zulo3d THANK YOU ALL FOR HELPING!
So basically i’m new to coding and using unity and dont understand most of it but i put this code together that somewhat works but also dosn’t here it is
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
public Rigidbody2D myrigidbody;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (!Input.GetKeyDown(KeyCode.A))
{
if (Input.GetKeyDown(KeyCode.D))
myrigidbody.velocity = Vector2.right * 2;
if (Input.GetKeyUp(KeyCode.D))
myrigidbody.velocity = Vector2.right * 0;
}
else
if (!Input.GetKeyDown(KeyCode.D))
{
if (Input.GetKeyDown(KeyCode.A))
myrigidbody.velocity = Vector2.left * 2;
if (Input.GetKeyUp(KeyCode.A))
myrigidbody.velocity = Vector2.left * 0;
}
else {; }
}
}
So my Problem is that its completly normal when it move to the right when it moves its only when i click d but also stops yet when i click a it mvoes forever until I click D Does someone know how to fix this please someone help
using UnityEngine;
public class movement : MonoBehaviour
{
public Rigidbody2D myrigidbody;
void Start()
{
}
void Update()
{
if (Input.GetKey(KeyCode.A))
myrigidbody.velocity = Vector2.right * 2;
else if (Input.GetKey(KeyCode.D))
myrigidbody.velocity = Vector2.left * 2;
}
}
using UnityEngine;
public class movement : MonoBehaviour
{
public Rigidbody2D myrigidbody;
void Update()
{
myrigidbody.velocity += new Vector2(Input.GetAxisRaw("Horizontal"),0);
}
}
If you want the character to stop when no key is pressed, then this needs an additional else statement to cover the case when neither A nor D are pressed.
else
myrigidbody.velocity = Vector2.zero;
Electro_Defender50, it may help to look at the documentation for GetKeyDown and GetKey. GetKeyDown is only true for a single frame (a single Update) when the key is press. GetKey will return true on every frame where the key is held down.
Or they could just increase the rigidbody’s drag setting. Friction will also slow the rigidbody if it’s grounded.
But really my first example was just demonstrating how to read the keys, as we shouldn’t really be setting the velocity in this way. It’s usually better to add to the velocity as shown in my second example.