- Home /
Unity Player Smooth Left - Right Movement
Hi , I am learning Unity 3d . Now I want to move the player object (The Ball) , Left and right by Left Arrow and Right Arrow key . I want smooth movement when the player goes left , but I don't know how to achieve that . I tried by multiplying by Time.deltaTime
but It is not working . When I press left arrow key , the player should move to -1 or +1 in Z axis , It is working but the movement is not smooth , it happens in a frame , which I don't want .
So can you help me how to get smooth transition ?
Here is my code :-
using UnityEngine;
using System.Collections;
public class Ball_Script : MonoBehaviour
{
private Rigidbody Ball_Rigid ;
public float Speed = 1 ;
// Use this for initialization
void Start ()
{
Ball_Rigid = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update ()
{
Ball_Rigid.AddForce (new Vector3 (-10 * Speed , 0 , 0));
if(Input.GetKeyDown(KeyCode.LeftArrow))
{
Ball_Rigid.MovePosition(new Vector3(transform.position.x , transform.position.y , transform.position.z - 1.0f));
}
if(Input.GetKeyDown(KeyCode.RightArrow))
{
Ball_Rigid.MovePosition(new Vector3(transform.position.x , transform.position.y , transform.position.z + 1.0f));
}
}
}
Here is Screen Shot :-
I Hope you help me :) Thanks
Answer by Neolith998 · Jan 08, 2016 at 08:25 PM
I'd suggest using Lerp to smooth everything out:
Vector3 pos;
GameObject objectToMove;
void Update()
{
Ball_Rigid.AddForce (new Vector3 (-10 * Speed , 0 , 0));
if(Input.GetKeyDown(KeyCode.LeftArrow))
{
pos = new Vector3(transform.position.x , transform.position.y , transform.position.z - 1.0f));
}
if(Input.GetKeyDown(KeyCode.RightArrow))
{
pos = new Vector3(transform.position.x , transform.position.y , transform.position.z + 1.0f));
}
objectToMove.transform.position = Vector3.Lerp(objectToMove.transform.position, pos, Speed * Time.deltaTime);
}
Not sure if this is exactly what you aim for, but here it is anyway.
Have fun.
Your answer
Follow this Question
Related Questions
Similar movement to a game (look description) 1 Answer
Translating Player Movement and Clipping Through Walls 2 Answers
Why am I only allowed to trigger my dash script once? 2 Answers
My animation is overriding my character movement? 2 Answers
How do I stop my player or camera from jittering during player movement? 1 Answer