- Home /
How to smooth movement object in one-axis?
Hello everyone, so i have a problem. I already can move the object by +2f, and set a limit position, But there is a problem. The problem is that i cant move it smoothly, i dont know how to do it, since im still a newbie. Is there anyone willing to help me? Thank you! Also i will give the code.
CODE:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class test : MonoBehaviour { public float stepHeight = 2f; public float minY, maxY;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.UpArrow))
{
transform.position = new Vector3(transform.position.x, transform.position.y + stepHeight, transform.position.z);
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
transform.position = new Vector3(transform.position.x, transform.position.y - stepHeight, transform.position.z);
}
transform.position = new Vector3(transform.position.x, Mathf.Clamp(transform.position.y, minY, maxY), transform.position.z);
}
}
Comment
Answer by BarelyUsedDesert · Sep 17, 2021 at 12:54 PM
I'm not sure if that's what you want, but if I'm right, you should use transform.Translate.
//speed of your object
public float speed = 5f;
//Time.deltaTime makes your speed independent from the player's framerate.
void Update(){
transform.Translate(speed * Vector3.up * Input.GetAxis("Vertical") * Time.deltaTime);
}
Also, remember that Input.GetKeyDown only triggers when the key is pressed down. Not when it's hold down or anything similar.