- Home /
Getting a character to fly(follow cursor in 2D) in Unity4.3
I've created a script based on the look at mouse script in the UnityWiki. I attached it to my player and when I run the script he just sits there, no reaction. Any ideas? I'm fairly noobish so it's probably something simple. Thanks! Code:
using UnityEngine;
using System.Collections;
public class Flying : MonoBehaviour {
public float speed;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void FixedUpdate ()
{
if (Input.GetKeyDown(KeyCode.LeftShift))
{
// Generate a plane that intersects the transform's position with an upwards normal.
Plane playerPlane = new Plane(Vector3.up, transform.position);
//Generate a ray from cursor position
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
// Determine the point where the cursor ray intersects the plane.
// This will be the point that the object must look towards to be looking at the mouse.
// Raycasting to a Plane object only gives us a distance, so we'll have to take the distance,
// then find the point along that ray that meets that distance. This will be the point
// to look at.
float hitdist = 0.0f;
if (playerPlane.Raycast (ray, out hitdist))
{
// Get the point along the ray that hits the calculated distance
Vector3 targetPoint = ray.GetPoint(hitdist);
//determine the target rotation. This is the rotation if the transform looks at the target
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
// Smoothly rotate towards the target point.
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.time);
//Move forward
transform.position = transform.forward *speed *Time.deltaTime;
}
}
}
}
Comment
Damn, I'm really new and only came to Unity for the 2d support. Could you help me translate it to 2d?
Your answer
Follow this Question
Related Questions
I want to click on my screen and make my character move there, having trouble with raycasts. 1 Answer
object rotates toward mouse? 2D Top Gameplay 6 Answers
How to make a 2d mouse look script 3 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
BoxCast, OverlapArea, and Raycasting; ground detection questions 0 Answers