Search Unity

Sprite shaking after movement

Discussion in 'Physics' started by Wandererz, Aug 15, 2017.

  1. Wandererz

    Wandererz

    Joined:
    Mar 4, 2015
    Posts:
    1
    Hello,
    I have a 2D sprite with a collider and rigibody which I click to move to a transform defined by mouseclick, calculating the relative position and then adding velocity.
    But after the movement it goes ever so slightly over the destination and then back to before the destination and that just keeps going on until another movement happens and if thats finished it starts all over again.
    I have an if function which tests if it reached destination and then setting the velocity to vector3.zero but it never does reach even if it goes over.
    In said if function I have put every test of trying to add a small margin of error including just testing for larger of smaller then, just getting the exact position and adding a margin of error using mathf clamp.
    I have red a lot of forum posts on this sort of problem but my solution isn't in it.
    This post is in the physics forum because I've concluded that it has to be something with the rigibody.
    But here is still the full very nooby script:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class PlayerController : MonoBehaviour {

    public Vector3 target;
    public float speed;
    public bool isMoving;
    public float error;

    // Use this for initialization
    void Start ()
    {
    target = transform.position;
    isMoving = false;
    }

    // Update is called once per frame
    void Update ()
    {

    target.z = 0;

    if (Input.GetMouseButtonDown(0))
    {
    isMoving = true;
    target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Debug.Log("Target Set" + target);
    }

    Vector3 relativePos = target - transform.position;

    transform.gameObject.GetComponent<Rigidbody2D>().velocity = relativePos.normalized*Time.deltaTime*speed;

    if (target.x == transform.position.x && target.y == transform.position.y || Mathf.Clamp(transform.position.x, transform.position.x - error, transform.position.x + error) == target.x && Mathf.Clamp(transform.position.y, transform.position.y - error, transform.position.y + error) == target.y || transform.position.x > target.x - error && transform.position.y > target.y - error && transform.position.x > target.x + error && transform.position.y > target.y + error && transform.position.x > target.x + error && transform.position.y > target.y - error && transform.position.x > target.x - error && transform.position.y > target.y + error)
    {
    gameObject.GetComponent<Rigidbody2D>().velocity = Vector3.zero;
    Debug.Log("Destination Reached");
    isMoving = false;
    }
    }
    }