- Home /
Swerve mechanic, Move left and right with touch
Hello, I am making a hyper casual game and I am stuck at the movement I want to implement the swerve mechanic but it is not working. I am using the deltaposition.x of the touch it works fine moves left and right but it is so laggy, stutters a lot.
Code:
private void Start()
{
characterController = GetComponent<CharacterController>();
gameManager = FindObjectOfType<GameManager>();
}
private void Update()
{
dir.z = forwardSpeed;
forwardSpeed += 0.01f * Time.deltaTime;
forwardSpeed = Mathf.Clamp(forwardSpeed,4.5f,7.5f);
if(Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
{
xAxis = touch.deltaPosition.x * sideSpeed * Time.deltaTime;
dir.x = xAxis;
}
if(touch.phase == TouchPhase.Ended)
{
dir.x = 0;
}
}
if(characterController.isGrounded == true && dir.y < 0)
{
dir.y = 0;
}
else
{
dir.y += gravity * Time.deltaTime;
}
}
private void FixedUpdate()
{
if(gameManager.gameOver == false && gameManager.gameStarted == true)
{
characterController.Move(dir * Time.deltaTime);
}
}
} `
Answer by DenisIsDenis · Jun 25, 2021 at 03:11 AM
When you assign dir.x
and dir.y
, you already multiply them by Time.deltaTime, which makes them scaled to work only in the Update()
function, and of course not in FixedUpdate()
.
So just remove the FixedUpdate()
function and add at the end of the Update()
function:
if(gameManager.gameOver == false && gameManager.gameStarted == true)
{
characterController.Move(dir);
}
You may need to adjust the speed after that, but it's not difficult.
In addition, deltaPosition
will only work correctly in Update()
.
I did it but still the same. When moving left right it starts to stutter
I have no motion stuttering in your modified script. Maybe something interferes with the movement from the outside. Describe how the movement to the left (right) stutters, the reason may become clear.
(Did you exactly write characterController.Move (dir);
without Time.deltaTime
? If not, that might be the reason).
Thank you very much for the help I found a way how to do it and it works perfectly without any problem this is the code I am using for the people who want to know
private float startTouch;
private float swipeDelta;
private void Update()
{
if(Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Began)
{
startTouch = touch.position.x;
}
if (touch.phase == TouchPhase.Moved || touch.phase == TouchPhase.Stationary)
{
swipeDelta = touch.position.x - startTouch;
startTouch = touch.position.x;
}
if(touch.phase == TouchPhase.Ended)
{
swipeDelta = 0;
}
}
dir.x = swipeDelta * sideSpeed;
}