C# script to make GameObject go to point showed by mouse cursor.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// © 2017 TheFlyingKeyboard
// theflyingkeyboard.net

public class MoveToPoint : MonoBehaviour {
    public float moveSpeed;
    public float rotationSpeed;

    private Vector3 target;
    // Use this for initialization
    void Start () {
        target = transform.position;
    }
  
  // Update is called once per frame
  void Update () {
        if (Input.GetMouseButtonDown(0))
        {
            target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        }

        transform.position = Vector2.Lerp(transform.position, target, moveSpeed);

        Vector3 vectorToTarget = target - transform.position;
        float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
        Quaternion qt = Quaternion.AngleAxis(angle, Vector3.forward);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, qt, Time.deltaTime * rotationSpeed);
    }
}

 

Unity 2D C# Go To Point Showed By Mouse Cursor
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *