- Home /
Mouse steering of physics sphere
Hi - I followed the roll - a - ball tutorial, currently WASD controls directional "addforce" movement
How would i script in C# to get my ball to look at my mouse cursor? to give you an idea my ball might have guns on it soon so id like to have an aiming system. so basically i need my ball to look at the position of the mouse and move towards or away from it ( in its direction) when W or S is pressed
here is my current playercontroller code
using UnityEngine;
using System.Collections;
public class playercontroller : MonoBehaviour {
public float speed;
private int count;
public GUIText countText;
// Use this for initialization
void Start () {
count = 0;
setcounttext ();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);
rigidbody.AddForce (movement * speed * Time.deltaTime);
}
void OnTriggerEnter(Collider other)
{
Debug.Log("trigger");
if (other.gameObject.tag == "pickup")
{
other.gameObject.SetActive(false);
count = count + 1;
setcounttext();
}
}
void setcounttext()
{
countText.text = "Count : " + count.ToString();
}
}
I have tried a few scripts that i found online but to no avail - i am beginner/moderate in C# but do not understand enough about transforms to get this without help :/
Answer by Socrates · Mar 25, 2015 at 09:01 AM
First, I highly recommend working through the Survival Shooter tutorial on the Unity Learn section. That is where the turning code below comes from.
Second, including this code should make your character turn toward the mouse cursor, assuming that your floor is tagged appropriately.
private Rigidbody playerRigidbody;
private int floorMask;
private float camRayLength = 100f;
void Awake()
{
floorMask = LayerMask.GetMask("Floor");
playerRigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
Turning();
}
void Turning()
{
Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit floorHit;
if(Physics.Raycast(camRay, out floorHit, camRayLength, floorMask))
{
Vector3 playerToMouse = floorHit.point - transform.position;
playerToMouse.y = 0f;
Quaternion newRotation = Quaternion.LookRotation(playerToMouse);
playerRigidbody.MoveRotation(newRotation);
}
}
Third, if you find your movement isn't going according to plan, take a look at world versus local space; meaning are you you applying force in a world space direction or based on the rotation of the character?
Your answer