Home > front end >  I want the character to walk not only in x but also in y
I want the character to walk not only in x but also in y

Time:05-15

I want the character to walk not only in x but also in y

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
        
        
public class Control : MonoBehaviour
{
    public float speed; // speed
    private float input; 
        
    private Rigidbody2D rb; // player
        
    public Animator anim; // player animator
    public Joystick joystick; // player joystick
        
    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
    }

    private void FixedUpdate()
    {
        input = joystick.Vertical;
        rb.velocity = new Vector2(input * speed, rb.velocity.y);
    }
}

I want the character to walk not only in x but also in y

CodePudding user response:

To simply just make it work you could just modify your code like this:

private Vector3 change;
// Declare private property above functions

private void FixedUpdate()
{
    change.x = joystick.Horizontal;
    change.y = joystick.Vertical;
    change = change.normalized;
    rb.MovePosition(rb.transform.position   change * speed * Time.fixedDeltaTime);
}

You are doing correctly that you're moving rb in FixedUpdate, but updating input would actually be better in normal update. So best option is:

private Vector3 change;
// Declare private property above functions

private void Update()
{
    change.x = joystick.Horizontal;
    change.y = joystick.Vertical;
    change = change.normalized; // Correct diagonal movement speed
}
private void FixedUpdate()
{
    rb.MovePosition(rb.transform.position   change * speed * Time.fixedDeltaTime);
}

Also, in this case in 2D, I think that you must actually use Vector3 to make it work correctly with transform.position rb.MovePosition().

  • Related