- Home /
Character rotation and move to mouse click point with speed
I need simulate forward rotation of the character in my 2D game project.
I have tried to create my movement script but it doesn't works perfect. The reason is my 2D actor is spaceship and it can't do rotation around his axis but i need just forward rotation for it.
Like this:
My script code is:
using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour {
public float speed = 1.5f;
public float rotationSpeed = 90f;
private Vector3 pos;
private Quaternion qTo;
void Start () {
pos = transform.position;
qTo = transform.rotation;
}
void Update () {
if (Input.GetMouseButtonDown(0) || Input.GetMouseButton(0)) {
pos = Input.mousePosition;
pos.z = transform.position.z - Camera.main.transform.position.z;
pos = Camera.main.ScreenToWorldPoint(pos);
}
var dir = pos - transform.position;
if (dir != Vector3.zero) {
qTo = Quaternion.LookRotation(Vector3.forward, pos - transform.position);
transform.rotation = Quaternion.RotateTowards (transform.rotation, qTo, Time.deltaTime * rotationSpeed);
}
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
}
}
Please help me to correct my script for more proper rotation and moving. Thank you
desired-movement.png
(145.8 kB)
Comment
Your answer
Follow this Question
Related Questions
Rotating an object towards target on a single axis 2 Answers
How can I rotate my player to look at the direction my Joystick is pointing to? (Top-Down 2D) 3 Answers
Unity 2D: How can i get my sprite to rotate to the direction I am going? 1 Answer
Accurate placed object's transform messes up on game start 1 Answer
Random Movement : 2d 1 Answer