- Home /
Code working for tutorial guy but not for me.
https://hatebin.com/ubijezrtpz Here is the code, it is supposed to move the character left and right when pressing A and D but it doesn't. Is something wrong with my code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public Rigidbody2D rb;
public float speed = 7;
public float moveInput;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
moveInput = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
}
}
Did you add the script to your game object? Does that gameobject have a Rigidbody2D?
Answer by henkehedstrom · Jan 12 at 04:52 PM
Nothing seems wrong with your code, I added it to a project and it worked for me. Is nothing happening at all? Make sure to add a RigidBody2D component to the object that has this script. The speed could also be set to 0 in the inspector which would be a problem.
Some tips on the code: Every variable that you have there could (and probably should) be private. The Rigidbody2D variable rb could be private because you set it in the Start function. The moveinput could be private because you set it in the FixedUpdate function. The speed could be private but you probably want it as a SerializeField to still be able to change it in the inspector.
I would change it to :
private Rigidbody2D rb;
[SerializeField] private float speed = 7;
private float moveInput;
Your answer
Follow this Question
Related Questions
Checking GameObject Position on Andriod 1 Answer
How do I slow down while Im Sliding? 0 Answers
Add Force At Player 0 Answers
Player stops moving upon collision 0 Answers