How to script a player following a mouse input?

Updated on February 22, 2018 in  [R] Scripts
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
3 on February 10, 2018

I am making a game which has movement like agar.io, it is top-down view but it’s 3D, I want the player to follow the mouse like in agar.io. This is my current code, but it uses WASD for movement.

public float gravity = 18.0F;
public float speed = 6.5F;
private Vector3 moveDirection = Vector3.zero;
void Update()
 {
 CharacterController controller = GetComponent<CharacterController>();
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
 moveDirection = transform.TransformDirection(moveDirection);
 moveDirection *= speed;
moveDirection.y -= gravity * Time.deltaTime;
 controller.Move(moveDirection * Time.deltaTime);
}
  • Liked by
Reply
1 on February 11, 2018

[1]: Add GameObject of type ‘ Quad ‘ to your scene.

[2]: Rotate X-axis of it to 90 degree.

[3]: Scale it to fit your ground by change X and Y of it.

[4]: Remove Mesh Renderer component from it.

[5]: Add new layer and rename it to ‘ Ground ‘ or any name you want.

[6]: This is your script after i updated it:

 

public float gravity = 18.0F;
public float speed = 6.5F;
private Vector3 moveDirection = Vector3.zero;
private int groundLayerNumber;
void Start()
{
groundLayerNumber = LayerMask.GetMask("Ground");
}
void FixedUpdate()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, Mathf.Infinity, groundLayerNumber ))
{
Vector3 mousePosition = hit.point - transform.position; mousePosition.y = 0f;
CharacterController controller = GetComponent<CharacterController>();
moveDirection = newVector3(mousePosition.x, 0, mousePosition.z);
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
moveDirection.y -= gravity * Time.deltaTime;
 controller.Move(moveDirection * Time.deltaTime);
 }
}

[7]: Add script to your player.

on February 11, 2018

Thank you very much, it works 🙂

Show more replies
  • Liked by
Reply
Cancel