Search Unity

Follow mouse script steers off unpredictably

Discussion in 'Scripting' started by pannakakor, Oct 4, 2018.

  1. pannakakor

    pannakakor

    Joined:
    Oct 4, 2018
    Posts:
    3
    Hi,

    I can't figure this one out.

    I have a simple script that raycast's the screen, assigns a dummy object to the location of that raycast, then the script moves my main character model towards the dummy object. In essence, when you hold down the mouse button, your character runs towards the mouse cursor location. Simple enough.

    This works perfectly on a flat plane, but when I run the character up a ramp, it always steers away from my mouse location until the character is back on flat ground (position.y = 0).

    Code (CSharp):
    1.         // Grab mouse position, then we assign a dummy object to that position
    2.         ray = cam.ScreenPointToRay(Input.mousePosition);
    3.         if (Physics.Raycast(ray, out hit, 50.0f, layerMask))
    4.         {
    5.             pointerCube.transform.position = hit.point;
    6.         }
    7.  
    8.         // Find the vector direction from the model we want to move to the dummy object
    9.         _direction = (pointerCube.transform.position - currentBody.transform.position).normalized;
    10.         _direction.y = 0;
    11.  
    12.         // Rotate towards the dummy object
    13.         _lookRotation = Quaternion.LookRotation(_direction);
    14.  
    15.         currentBody.transform.rotation = _lookRotation;
    16.  
    17.         // Feed speed into animator, calculated elsewhere in script
    18.         animatorController.AnimateMovement(currentSpeed, 0);
    Any ideas what I can do to solve the rotation issue? The character is non-kinematic rigidbody. I feel like I'm overlooking something painfully simple, so there may be details I'm omitting in my question, but I thought I would ask.
     
  2. Cyber-Dog

    Cyber-Dog

    Joined:
    Sep 12, 2018
    Posts:
    352
    Just some things that grab my attention...

    Your using a layer-mask, is the ramp being detected?
    Maybe Debug.Log() the hit.point. and check that the ramp is being collided against.
    I mentioned that in case your dummy object is invisible.

    Let me know, I will take another look if that is not it.