How to make a 8 directional key input movement?
Im using c#. I use the case structure to move my object in the plane im using, but cant seem to move it at and angle. Using the "wasd" i was able to move fowards, backwards, and to the sides buy cant use, for example, "w" and "d" to move at a angle. i keep attempting to use the case by adding the new key input and did not work, i also used "&&" but it did not help me either. Any help out there?
Also, any improvement is welcome.
using UnityEngine;
public class Movment : MonoBehaviour {
public Rigidbody rb;
// Update is called once per frame
void FixedUpdate ()
{
string caseSwitch = Input.inputString;
switch (caseSwitch)
{
//working "wasd" movement without the angle movement
case "d":
rb.AddForce(x: 1000 * Time.deltaTime, y: 0, z: 0);
break;
case "w":
rb.AddForce(x: 0, y: 0, z: 1000 * Time.deltaTime);
break;
case "a":
rb.AddForce(x: -1000 * Time.deltaTime, y: 0, z: 0);
break;
case "s":
rb.AddForce(x: 0, y: 0, z: -1000 * Time.deltaTime);
break;
//angle axis movement attempt
case "d" + "w":
rb.AddForce(x: 1000 * Time.deltaTime, y: 0, z: 1000 * Time.deltaTime);
break;
case "w" + "a":
rb.AddForce(x: -1000 * Time.deltaTime, y: 0, z: 1000 * Time.deltaTime);
break;
case "a" + "s":
rb.AddForce(x: -1000 * Time.deltaTime, y: 0, z: -1000 * Time.deltaTime);
break;
case "s" + "d":
rb.AddForce(x: 1000 * Time.deltaTime, y: 0, z: -1000 * Time.deltaTime);
break;
default:
rb.AddForce(x: 0, y: 0, z: 0);
break;
}
}
}
Answer by Hellium · Oct 12, 2017 at 08:07 AM
Keep it simple :
void FixedUpdate ()
{
Vector3 force = new Vector3();
if( Input.GetKey(KeyCode.Keycode.A ) force.x = -1000 ;
else if( Input.GetKey(KeyCode.Keycode.D ) force.x = 1000 ;
if( Input.GetKey(KeyCode.Keycode.S ) force.z = -1000 ;
else if( Input.GetKey(KeyCode.Keycode.W ) force.z = 1000 ;
rb.AddForce( force * Time.deltaTime );
}
Your answer
Follow this Question
Related Questions
My C# gave me inverted controls for left and right WASD movement? 1 Answer
Anyone have any ideas on how I could improve my character jump to make it more realistic? 1 Answer
Moving an object slower, in clockwise motion, around a pivot with Quaternion.AngleAxis 0 Answers
How do i change a color of an individual alphabet of a UI.Text 2 Answers