I am developing a 2D game level, but making it in a 3D environment using Unity3d and c# coding. Now i can not get the exact position for my character although it says that it is, (the vector 3 of my wanted position and my character position matches) but not in the screen,...
this is my code:
using UnityEngine;
using System.Collections;
public class WalkToPoint : MonoBehaviour
{
public Vector3 tar;
public float speed;
private Vector3 mousePos;
private Vector3 relativePos;
Camera main;
Animator anim;
bool isWalking = false;
Vector3 target;
float x, y, z;
[HideInInspector]
public bool
facingRight = true;
void Start ()
{
// y = transform.position.y;
// z = transform.position.z;
// tar.z = z;
main = Camera.main;
anim = GetComponent<Animator> ();
target = transform.position;
}
// Update is called once per frame
void Update ()
{
if (Time.time > 2 && GetComponent<Rigidbody2D> ().velocity.magnitude == 0) {
y = transform.position.y;
z = transform.position.z;
if (Input.GetMouseButton (0)) {
mousePos = Input.mousePosition;
mousePos.z = -53f;
mousePos.y = 0f;
target = main.ScreenToWorldPoint (mousePos);
target.x *= -1;
target.y = y;
target.z = z;
print (target);
relativePos = target - transform.position;
anim.SetFloat ("Speed", speed);
isWalking = true;
}
if (isWalking) {
/*x = transform.position.x;
x = Vector3.Lerp (transform.position, tar, Time.deltaTime * speed).x;
transform.position = new Vector3 (x, y, z);*/
transform.position = Vector3.MoveTowards (transform.position, target, speed * Time.deltaTime);
if (Mathf.Abs (target.x - transform.localPosition.x) <= 0.12f) {
isWalking = false;
anim.SetFloat ("Speed", 0f);
}
}
}
}
void FixedUpdate ()
{
if (relativePos.x > 0 && facingRight)
Flip ();
else if (relativePos.x < 0 && !facingRight)
Flip ();
}
void Flip ()
{
facingRight = !facingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}