xercool - 1 year ago 159
C# Question

# 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.

Here is a two parts of this movement.

• Actor must go forward and rotate to turn back (the radius must be optimal or pre-defined).

• Actor must go straight by line using mouse click location.

So. I use Unity engine. Need some explanations to release it.

Thank you!

UPD: My current source code:

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);
}

}

Answer Source

Try this:

var dir = pos - transform.position;
qTo = Quaternion.LookRotation(Vector3.forward, pos - transform.position);

if (Quaternion.Angle(transform.rotation, qTo) >= rotPrecision) //just set your own precision
transform.rotation = Quaternion.RotateTowards(transform.rotation, qTo, Time.deltaTime * rotationSpeed);

if(Vector3.Distance(transform.position,pos) > movePrecision) // 0.1f
transform.Translate(Vector3.up * speed * Time.deltaTime);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download