- Home /
Using WASD keys instead of mouse to roll ball?
Hey,
I am trying to use the W and S key in order to control a cube which I am just using for a demo... Below is the code I have found which allows me to use the mouse to move the cube and hit the Sphere... How can I make it so the cube is moved with WASD?
using UnityEngine; using System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class SphereMovement : MonoBehaviour { float ZSpeed = 1.0f; float XSpeed = 1.0f;
void Start()
{
rigidbody.freezeRotation = true;
rigidbody.drag = 5.0f;
Physics.maxAngularVelocity = 100.0f;
}
void Update()
{
rigidbody.AddForce(new Vector3(Input.GetAxis("Mouse X") * XSpeed
0, Input.GetAxis ("Mouse Y") * ZSpeed), ForceMode.Impulse);
}
void OnCollisionEnter(Collision other)
{
if(other.rigidbody)
{
if(!other.gameObject.GetComponent<ConstantForce>())
other.gameObject.AddComponent<ConstantForce>();
else
other.rigidbody.constantForce.force = rigidbody.velocity;
}
}
}
Thanks, John
Answer by TeohRIK · Dec 09, 2015 at 03:14 AM
Maybe try with this
rigidbody.AddForce(new Vector3(Input.GetAxis("Vertical") * XSpeed, 0.0f, Input.GetAxis ("Horizontal") * ZSpeed), ForceMode.Impulse);
If you look on the Input Manager, Vertical is use to get W and S key, Horizontal is A and D API reference: Input Manager
Cheers I think this is making me understand a bit... So if I where to move the other directions I would just add a negative to Vertical?... Would it be like "-Vertical" or what would I type... Sorry I'm a noob...
sorry, should be something like, Vertical should be on Z-axis, so it will move forward or backward
rigidbody.AddForce(new Vector3(Input.GetAxis("Horizontal") * XSpeed, 0.0f, Input.GetAxis ("Vertical") * ZSpeed), Force$$anonymous$$ode.Impulse);
Thanks alot will try that tomorrow, I think I messed up the placement of all my stuff in the game so need to fix that and try this out hopefully it works...