Fixed it myself
Setting Velocities through Input
With my code as it stands here the "Left" command and animation work fine but the "Right" Command does not.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float speed;
private bool moveR;
private bool moveL;
private Animator animator;
private Rigidbody2D rb;
void Start()
{
animator = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
bool right = Input.GetKey("right");
bool left = Input.GetKey("left");
if (right||left)
{
rb.velocity = new Vector2(0, 0);
}
if (right)
{
moveR = true;
rb.velocity = new Vector2(speed, 0);
}
else
{
moveR = false;
rb.velocity = new Vector2(0, 0);
}
animator.SetBool("runright", moveR);
//
if (left)
{
moveL = true;
rb.velocity = new Vector2(-speed, 0);
}
else
{
moveL = false;
rb.velocity = new Vector2(0, 0);
}
animator.SetBool("runleft", moveL);
}
}
My goal here is that I want the object to immediately be at a certain velocity upon pressing left or right then immediately stop when the button is released or if both are pressed at the same time. I do not understand why but only the "Left" input works as it stands. I am in 2D mode if that information helps. Thank you for your time.
I figured it out. The issue is that you cannot have multiple "if" statements in a single cell. The fix was to just put "else" before every if statement after the first. Thanks for your help and time though.
Answer by Abhiroop-Tandon · Mar 24, 2016 at 10:00 AM
It is a bit messed up but see if this works
void Update()
{
bool right = Input.GetKey("right");
bool left = Input.GetKey("left");
if (right && left)
{
rb.velocity = new Vector2(0, 0);
}
if (right)
{
moveR = true;
rb.velocity = new Vector2(speed, 0);
}
if (left)
{
moveL = true;
rb.velocity = new Vector2(-speed, 0);
}
else
{
moveR = false;
moveL = false;
rb.velocity = new Vector2(0, 0);
}
animator.SetBool("runleft", moveL);
animator.SetBool("runright", moveR);
}
let me know if this works
This does make it look a bit nicer but I'm still left with the same problem.
Follow this Question
Related Questions
How can i detect a collision with many Terrains?, since my collider is not working? 0 Answers
Script to make hand move in a punching motion not working? 0 Answers
Help with simple player movement 0 Answers
Photon 2 Enemy AI Doesn't move? 1 Answer
how to dostraight ball throwing objects from returning? 0 Answers