So I’m a beginner who is learning Unity because it seems fun, which it has been and I’ve been enjoying going though the tutorials which has honestly been excellent so far and I can’t praise this community enough for how much effort seems to have been put into making it easy for new people to dive into unity.
but enough brown nosing, here my problem that I have run into:
I have been going though the tutorial by Chris’ tutorials
2D Top Down Pixel Art RPG Game Dev in Unity 2022 ~ Crash Course Tutorial for Beginners - YouTube
and I have gotten half way though to where I am moving the player sprite around which works but is incredible slow.
what I have noticed is the “Move Speed” starts off with the value of 1 but when you click play and then press a move key it changes to 0.04.
I have double checked the code (See below) and I can’t see anything wrong with it but if I remove the Time.fixedDeltaTime from
rb.MovePosition(rb.position + (direction * moveSpeed * Time.fixedDeltaTime));
The sprite moves at a normal speed but the “Move Speed” still shows as 0.04, so I don’t think that this is the cause.
Does anyone have any ideas?
Before
https://ibb.co/T26gBjs
After
https://ibb.co/ZXYT2Qc
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 1f;
public float collisionOffset = 0.05f;
public ContactFilter2D movementFilter;
Vector2 movementInput;
Rigidbody2D rb;
List<RaycastHit2D> castCollisions = new List<RaycastHit2D>();
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
private void FixedUpdate()
{
// If movement input is not 0, try to move
if (movementInput != Vector2.zero)
{
bool success = TryMove(movementInput);
if (!success)
{
success = TryMove(new Vector2(movementInput.x, 0));
if (!success)
{
success = TryMove(new Vector2(0, movementInput.y));
}
}
}
}
private bool TryMove(Vector2 direction)
{
//Check for potential collisions
int count = rb.Cast(
movementInput, // X and Y values between -1 and 1 that represent the direction from the body to look for collisions
movementFilter, // The settings that determine where a collision can occur on such as layers to collide with
castCollisions, // List of collisions to store the found collisions into after the Cast is finished
moveSpeed = Time.fixedDeltaTime + collisionOffset); // the amount to cast equal to the moment plus an offset
if (count == 0)
{
rb.MovePosition(rb.position + (direction * moveSpeed * Time.fixedDeltaTime));
return true;
}
else
{
return false;
}
}
void OnMove(InputValue movementValue)
{
movementInput = movementValue.Get<Vector2>();
}
}