- Home /
Follow Player 2d
I got this script from another wonderful user on this forum and it works perfectly for what it was designed to do...
there are some problems though.... Is there any way this script can be made to work on the 2d setup of unity and remove the rotation by replacing it with just flipping the texture left and right?
var target : Transform;
var moveSpeed = 5;
var rotationSpeed = 5;
var myTransform : Transform;
function Awake () {
myTransform = transform;
}
function Start () {
target = GameObject.FindWithTag("Player").transform;
}
function Update () {
var dist = Vector3.Distance(target.position, myTransform.position);
var lookDir = target.position - myTransform.position;
lookDir.y = 0;
myTransform.rotation = Quaternion.Slerp( myTransform.rotation,
Quaternion.LookRotation(lookDir), rotationSpeed*Time.deltaTime );
if(dist < 10){
myTransform.rotation = Quaternion.Slerp( myTransform.rotation,
Quaternion.LookRotation(lookDir), rotationSpeed*Time.deltaTime );
if(dist > 0.5){
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
}
Answer by Superrodan · Jan 15, 2015 at 10:25 PM
Hi there,
I'm not an expert programmer, but I have an idea based on the code you posted. It seems you'd need to replace this chunk:
var lookDir = target.position - myTransform.position;
lookDir.y = 0;
myTransform.rotation = Quaternion.Slerp( myTransform.rotation,
Quaternion.LookRotation(lookDir), rotationSpeed*Time.deltaTime );
What about replacing that code with an if statement like this... I'm not sure what method you'd want to use to flip your sprite but whatever you decide to use you would put in the if statement.
if(target.position.x>=myTransform.position.x)
{
//Look right, since the target is to my right
}else{
//Look left, since the target is to my left
}
As for suggestions on how to look right or left, what I would try is to flip the scale of the visual part of your character/object doing the following.
If the sprite is looking right by default and is at a scale of 1, use this to flip it left:
var flipScale = myTransform.localScale;
scale.x=-1;
myTransform.localScale= flipScale;
Then to flip it back to the right it would be this:
var flipScale = myTransform.localScale;
scale.x=1;
myTransform.localScale= flipScale;
Your answer
Follow this Question
Related Questions
Smooth Camera 2D Follow Player 0 Answers
Enemy reorienting for player 1 Answer
AI follows player between platforms in 2D? 1 Answer
Cinemachine 2d camera problem 0 Answers