Search code examples
c#unity-game-engine2dtop-down

character keeps shaking while in topdown shooter


ok well i am working on a top down shooter i have made my character look at the mouse using screentoworld view and i made my camera follow my players x, and z axis but anytime my character moves parallel from the mouse it starts shaking I think its because it looks at the mouse an the mouse real world position is dependent on the cameras position which is, but i am not sure.

here is the playerscript the many backslashes showed other things I've tried

gameObject.GetComponent<Rigidbody>().velocity = new Vector3(Input.GetAxisRaw("Horizontal")*movementspeed,0,Input.GetAxisRaw("Vertical")*movementspeed);  
        if (gameObject.GetComponent<Rigidbody> ().velocity.x != 0 && gameObject.GetComponent<Rigidbody> ().velocity.z != 0) {
            gameObject.GetComponent<Rigidbody>().velocity = new Vector3(Input.GetAxisRaw("Horizontal")*movementspeeddiag ,0,Input.GetAxisRaw("Vertical")*movementspeeddiag); 
        }

    // makes vector 3 type target equall to mouse position on pixial cordinates converted in to real world coordniates
        target = camera.ScreenToWorldPoint (new Vector3(Input.mousePosition.x,Input.mousePosition.y,camera.transform.position.y - transform.position.y)); 

        //Vector3 newtarget = target - transform.position;

        //lerptarget = Vector3.Lerp (transform.eulerAngles,newtarget, 100);
        // states the vector 3 values of target 

        // makes object local z face target and iniziates up axis 

        //Quaternion rotation = Quaternion.LookRotation (newtarget, Vector3.up); 

        //transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle (transform.eulerAngles.y, rotation.eulerAngles.y, rotatespeed * Time.deltaTime);
        transform.LookAt (target,Vector3.up);

and camera script

    void LateUpdate(){
        position = new Vector3 (player.transform.position.x, 10, player.transform.position.z); 
        transform.position = position;
        //transform.localPosition = Vector3.Lerp (transform.position, position, speed *Time.deltaTime); 

        transform.eulerAngles = new Vector3 (90,0,0); 
    }

Solution

  • Probably, the problem is that you change the velocity of rigidbody. Becouse velocity changes applied each fixed update time interval, it doesnt match with frame updating time, and may lead to shaking. According to unity docs you should try to avoid directly changes of velocity. (http://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html)

    I'd suggest you to you use MovePosition alongside with Lerp function to implement player movement. See this: http://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html