Unity Horizontal Input is Always -1 - c#

Whenever I'm making a game (3D or 2D) and I use Input.GetAxis("Horizontal"); Without pressing any buttons, my input is always -1. This problem only shows up with Unity.
Inputs for Unity
To test, I played other video games (some made with Unity & some not made with Unity) and they work fine. Only one or two games made with Unity kept thinking I'm holding down either the left arrow key or the "A" key.
While in play mode, if I press the "D" key, I'll move to the right and when I take my finger off the key, it moves back to the left as if I'm pressing the "A" key.
Somethings when I enter play mode, the Vertical Input will also receive inputs that are not given.
Note: This happens at the very start (when I click the play button).
Console & Game (no inputs by me)
Same Input in a UI Scene
My Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMovement : MonoBehaviour
{
public float moveSpeed = 5f;
private Rigidbody2D rb;
private Vector2 moveDirection;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
ProcessInputs();
}
private void FixedUpdate()
{
Move();
}
void ProcessInputs()
{
float moveX = Input.GetAxis("Horizontal");
float moveY = Input.GetAxis("Vertical");
print("X: " + moveX + " | Y: " + moveY);
moveDirection = new Vector2(moveX, moveY).normalized;
}
void Move()
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
}
}

Related

How to fix move with wasd while using Cinemachine

PICTURE : https://i.stack.imgur.com/O9T5t.png
Hi, I just recently tried the tutorial of Roll A Ball in Unity. In the tutorial you only taught how camera follow the ball from 1 fixed point. But I want to edit so that the camera will always behind the ball to follow and they key WASD always the same. Its like openworld game such as GTA V, RDR2, etc..
I tried using Cinemachine for vcam and freelookcam, it works for the camera to follow but the key WASD messed up for example W should be for forward, but right now its moving backward.
Here is my PlayerController code for moving the player, I believe its on the OnMove function.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
// Include the namespace required to use Unity UI and Input System
using UnityEngine.InputSystem;
using TMPro;
public class PlayerController : MonoBehaviour
{
// Create public variables for player speed, and for the Text UI game objects
public float speed;
public TextMeshProUGUI countText;
public GameObject winTextObject;
private float movementX;
private float movementY;
private Rigidbody rb;
private int count;
// At the start of the game..
void Start()
{
// Assign the Rigidbody component to our private rb variable
rb = GetComponent<Rigidbody>();
// Set the count to zero
count = 0;
SetCountText();
// Set the text property of the Win Text UI to an empty string, making the 'You Win' (game over message) blank
winTextObject.SetActive(false);
}
void FixedUpdate()
{
// Create a Vector3 variable, and assign X and Z to feature the horizontal and vertical float variables above
Vector3 movement = new Vector3(movementX, 0.0f, movementY);
rb.AddForce(movement * speed);
}
void OnTriggerEnter(Collider other)
{
// ..and if the GameObject you intersect has the tag 'Pick Up' assigned to it..
if (other.gameObject.CompareTag("PickUp"))
{
other.gameObject.SetActive(false);
// Add one to the score variable 'count'
count = count + 1;
// Run the 'SetCountText()' function (see below)
SetCountText();
}
}
void OnMove(InputValue value)
{
Vector2 v = value.Get<Vector2>();
movementX = v.x;
movementY = v.y;
}
void SetCountText()
{
countText.text = "Count: " + count.ToString();
if (count >= 12)
{
// Set the text value of your 'winText'
winTextObject.SetActive(true);
Time.timeScale = 0;
}
}
}
To solve this problem you have to adjust the input axis according to the camera.
Transform.TransformDirection("// input vector..");
With low corrections the problem may be solved.
void FixedUpdate()
{
Vector3 movement = new Vector3(movementX, 0.0f, movementY);
// affect base on camera direction
movement = Camera.main.transform.TransformDirection(movement);
movement.y = 0;
rb.AddForce(movement.normalized * speed);
}

movement with 3D sprite in unity is not working

I had gotten all the movement working with my ghost, which was a red ball, so i made a sprite (im not sure if that is what you call it) i was able to make one but now the movement is not working. it looks like it is on ice because when it tries to turn it goes diagonal and it speeds up when going straight. I don't know why its doing this because i'm not even putting force into it to move it. (the code):
GameObject.Find("ghosteyes").transform.position = (place + vecmove);
thanks
so what you can do is 3 things. first get your transform,then move it using Translate like this:
private Transform _transform;
private void Start()
{
//this gets the transform that the script is on and sets it to _transform
_transform = this.GetComponent<Transform>();
}
private void Update()
{
float hor = Input.GetAxis("Horizontal");
float vert = Input.GetAxis("Vertical");
_transform.Translate(new Vector2(hor, vert));
}
OR
Add the Input to the position for a more fixed movement.
private Transform _transform;
private void Start()
{
//this gets the transform that the script is on and sets it to _transform
_transform = this.GetComponent<Transform>();
}
private void Update()
{
float hor = Input.GetAxis("Horizontal");
float vert = Input.GetAxis("Vertical");
_transform.position += new Vector3(hor,vert) * Time.deltaTime;
}
OR
create a rigidBody on your player. then put this script on your player. and use rigidbody.MovePosition to move your character. for example:
private Rigidbody2D rb;
private void Start()
{
rb = this.GetComponent<Rigidbody>();
}
private void Update()
{
//This will take in horizontal input like A and D/ arrow left or right.
float hor = Input.GetAxis("Horizontal");
rb.MovePosition(transform.position += new Vector2(hor,0));
}

How can I do the swipe?

I have a game made with unity, subway surfers like, everything it's done BUT:
On the laptop I can use the arrow keys for left and right to move the player but on the phone I can't, no button, no tilt, no swipe, nothing.
I attached my script here, please help me with some controls, but to be the same value with left and right.
Thank you!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[Range(-2, 2)] public float value;
public float Speed;
Rigidbody rigid;
private Transform player;
private Vector3 desiredPosition;
void Start()
{
rigid = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
transform.position = new Vector3(value, transform.position.y, transform.position.z);
rigid.velocity = (Vector3.forward * Time.deltaTime * Speed);
}
private void LateUpdate()
{
if (Input.GetButtonDown("Right"))
{
if (value == 2)
return;
value += 2;
}
if (Input.GetButtonDown("Left"))
{
if (value == -2)
return;
value -= 2;
}
}
}
I would say that you need to find the position of the finger at the start using touch.position. Make sure that the touch is a touch. Then keep finding the position of the touch until it has traveled as far as you want it to. Then, call the function which moves the character. This unity documentation may help you as well with touch input.
https://docs.unity3d.com/ScriptReference/Touch.html

My player prefab moves forward fine until it hits an object, what is going on?

I'm making a unity game based off of TierZoo, and while testing a movement script, i crashed into one of the rigidbody trees for fun... and that made the player prefab stop moving forward, and it started moving in odd directions Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewPlayerController : MonoBehaviour
{
private Rigidbody rb;
public GameObject player;
public float thrust = 1.0f;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.W))
{
rb.AddRelativeForce(player.transform.right * thrust * 2.5f);
}
if (Input.GetKey(KeyCode.A)) { player.transform.Rotate(0, -1, 0); }
if (Input.GetKey(KeyCode.D)) { player.transform.Rotate(0, 1, 0); }
if (Input.GetKey(KeyCode.S))
{
rb.AddRelativeForce(player.transform.right * thrust * -2.5f);
}
}
}
If you can find a way to fix this, let me know.
You could fix the rotation also in Y direction by keeping track of it and setting it hard in FixedUpdate.
In general as said in the comments:
Whenever a Rigidbody is involved you should not
do movements through the transform component
do movements in Update
both breaks the physics engine and you might get strange and unexpected movements or simply no collisions working etc.
Rather do
- go through the Rigidbody component e.g. using MovePosition and MoveRotation
- do these in FixedUpdate
these keeps the physics intact and moves your Rigidbody only e.g. until it collides meanwhile.
Then for the rotation you have framerate-dependent values Rotate(0, -1, 0)! You rather want to use Time.deltaTime in order to get smooth framerate-independent rotation speed - not in 1 degree per frame but rather e.g. 45 degrees per second.
You script could look like
public class NewPlayerController : MonoBehaviour
{
// already reference this via the Inspector
[SerializeField] private Rigidbody rb;
public GameObject player;
public float thrust = 1.0f;
private void Awake()
{
// as fallback get it on runtime
if(!rb) rb = GetComponent<Rigidbody>();
}
bool moveLeft;
bool moveRight;
bool rotateLeft;
bool rotateRight;
private float angle;
void Update()
{
// Get User input here
// (in your case it would be also fine to do it in FixedUpdate.
// What doesn't work in FixedUpdate are mainly the one-time events like GetKeyDown)
moveRight = Input.GetKey(KeyCode.W);
rotateLeft = Input.GetKey(KeyCode.A);
rotateRight = Input.GetKey(KeyCode.D);
moveLeft = Input.GetKey(KeyCode.S);
}
private void FixedUpdate()
{
if(moveRight) rb.AddRelativeForce(rb.rotation * Vector3.right * thrust * 2.5f);
if(moveLeft) rb.AddRelativeForce(rb.rotation * Vector3.right * thrust * -2.5f);
// Now for the rotations keep track of what you rotated already
// and overwrite the rotation with the fix value:
if(rotateLeft)
{
// e.g. for rotating 45°/second
angle -= -45 * Time.deltaTime;
rb.MoveRotation(Quaternion.Euler(0, angle, 0));
}
if(rotateRight)
{
angle += 45 * Time.deltaTime;
rb.MoveRotation(Quaternion.Euler(0, angle, 0));
}
}
}

I have followed a tutorial on making controls for a fps game on unity. the controls work but if I leave the controls then I keep moving to the left

enter image description hereI have made controls for my character to move along the X axis. They seem to be working fine but my character keeps moving left and I'm not sure why or what I have missed.I have posted code from the two separate scripts
I have rechecked his code several times.I have checked to see if my arrow keys, numpad keys and WASD are sticking or any other.
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMotor : MonoBehaviour
{
private Vector3 velocity = Vector3.zero;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
//gets a movement vector
public void Move (Vector3 _velocity)
{
velocity = _velocity;
}
//run every physics iteration
void FixedUpdate()
{
PerformMovement();
}
//perform movement based on velocity variable
void PerformMovement ()
{
if (velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
}
}
And the controller:
using UnityEngine;
[RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour
{
[SerializeField] //makes speed show up in inspector even if set to private
private float speed = 5f;
private PlayerMotor motor;
void Start ()
{
motor = GetComponent<PlayerMotor>();
}
void Update()
{
//Calculate movement velocity as a 3D vector
float _xMov = Input.GetAxisRaw("Horizontal");
float _zMov = Input.GetAxisRaw("Vertical");
Vector3 _movHorizontal = transform.right * _xMov;
Vector3 _movVertical = transform.forward * _zMov;
//final movement vector
Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;
//apply movement
motor.Move(_velocity);
}
}
I expect 0 output when not pressing buttons but it seems to make me move to the left at speed of 5
You have a controller connected and reporting a slight movement in one direction. Use Input.GetAxis instead of Input.GetAxisRaw to let Unity handle deadzone detection. This way, nearly neutral inputs will be treated as neutral inputs.
void Update()
{
//Calculate movement velocity as a 3D vector
float _xMov = Input.GetAxis("Horizontal");
float _zMov = Input.GetAxis("Vertical");
Vector3 _movHorizontal = transform.right * _xMov;
Vector3 _movVertical = transform.forward * _zMov;
//final movement vector
Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;
//apply movement
motor.Move(_velocity);
}

Categories

Resources