Weird mouse input which worked fine before

Updated on March 5, 2018 in  [R] Scripts
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
3 on March 3, 2018

This was discussed in the previous post:

http://forum.brackeys.com/thread/how-to-script-a-player-following-a-mouse-input/

But this time I was doing the same type of movement on another project which is multiplayer, but the controlling is weird on a local player, remote players are not working yet because I am currently working on a local.

The problem is when the mouse is directed upwards, the player goes upwards which is good, but when it’s directed downwards it goes again upwards, and when it is directed left or right, it goes upwards or downwards depending on the direction but never to the exact same spot where the mouse is located, it goes just a bit and that’s it.

This is my script:

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 = new Vector3(mousePosition.x, 0, mousePosition.z);
 moveDirection = transform.TransformDirection(moveDirection);
 moveDirection *= speed;
 moveDirection.y -= gravity * Time.deltaTime;
 controller.Move(moveDirection * Time.deltaTime);
 }
 }
  • Liked by
Reply
1 on March 5, 2018

If your goal is to make your character move towards the mouse position, I don’t get what you are doing at line 15. hit.point will be the position of your mouse projected onto the ground, I think you just want to use that as the target position for the movement. By doing that Vector3 subtraction, you are storing inside mousePosition the direction between the mouse position and your player. So when you then create your moveDirection at line 18, that’s not gonna work as I’m guessing you intend to. Can you try to comment out the lines 16 to 21, and pass to the controller.Move( mousePosition * Time.deltaTime) ?

on March 5, 2018

When the game starts, it snaps forward to a position and doesn’t move anymore

Show more replies
  • Liked by
Reply
Cancel
0 on March 5, 2018

Then I must ask, what does your controller.Move method do?

Another thing I forgot to mention, at line 15 you should normalize the subtraction by doing:

Vector3 mousePosition = (hit.point – transform.position).normalized;

This way your movements will only be relative to your movement speed, and not to the distance of the mouse

  • Liked by
Reply
Cancel