Hỏi đáp
Chia sẻ kiến thức, cùng nhau phát triển
[UNITY3D] Object không thể di chuyển tới vị trí click chuột.
20:59 31-01-2018
1.293 lượt xem
0 bình luận
Mình đang thử cho nhân vật di chuyển đến vị trí click chuột bằng raycast xuống 1 cái plane , có animation Idle và Walk, khi đến vị trí click thì sẽ chuyển từ walk về Idle. Nhưng khi click thì nhân vật ở chế độ walk hoài không về Idle, debug thì thấy là cái vị trí nhân vật không bao giờ đến được vị trí click. Đã thử cho camera vuông góc từ trên xuống nhưng vẫn chưa giải quyết được. Mọi người giúp với.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float speed = 1f;
public Vector3 target;
private bool flag;
Animator anim;
void Awake()
{
anim = gameObject.GetComponent<Animator> ();
}
void Start()
{
flag = false;
}
void Update()
{
GotoObj ();
Animating ();
Debug.Log ("Flag "+flag);
Debug.Log ("Mathf "+Mathf.Approximately (transform.position.magnitude, target.magnitude));
}
void GotoObj()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePos = Input.mousePosition;
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (mousePos);
if (Physics.Raycast(ray,out hit))
{
flag = true;
target = new Vector3 (hit.point.x, transform.position.y, hit.point.z);
}
}
if (flag &&!Mathf.Approximately(transform.position.magnitude,target.magnitude))
{
transform.LookAt (target);
transform.position = Vector3.Lerp (transform.position, target, speed*Time.deltaTime);
}
else if (flag && Mathf.Approximately(transform.position.magnitude,target.magnitude))
{
flag = false;
}
}
void Animating()
{
anim.SetBool ("IsWalk", flag);
}
/* void Touch_GotoObj()
{
if ((Input.touchCount >0 && Input.GetTouch(0).phase==TouchPhase.Began))
{
RaycastHit hit;
Ray ray=Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
if (Physics.Raycast(ray, out hit))
{
flag = true;
target = new Vector3(hit.point.x, 0f, hit.point.z);
}
}
if (flag && !Mathf.Approximately(transform.position.magnitude, target.magnitude))
{
transform.LookAt (target);
transform.position = Vector3.Lerp (transform.position, target, speed*Time.deltaTime);
}
}*/
}