raycasthit to set new move location
I am currently trying to use a raycasthit to check if im hitting a wall on mouseclick and if so, set the character to move to that position instead of the mouse position. Ive tried utilizing a few different methods but the current iteration I am using makes it so the player doesn't move at all.
This is my current player script:
using UnityEngine; using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float speed = 1.0f;
public bool moving = false;
public bool isMoving = false;
public float stopRange = .5f;
public float distance;
private Vector3 endPoint;
private Vector3 target;
private Rigidbody2D RB;
private Ray ray;
// Use this for initialization
void Start ()
{
//get the rigidbody on player
RB = GetComponent<Rigidbody2D> ();
}
// Update is called once per frame
void Update () {
distance = Vector3.Distance (endPoint, transform.position);
// if player is moving without mouse click
if (Input.GetMouseButtonDown (0) && !moving)
{
movement ();
}
//if the player is moving with mouse click
else if (Input.GetMouseButtonDown (0) && moving)
{
//stop the player from moving
RB.isKinematic = true;
movement ();
}
if (distance >= stopRange)
{
RB.MovePosition (transform.position + target * speed * Time.deltaTime);
}
else if (distance <= stopRange)
{
moving = false;
}
}
public void movement()
{
moving = true;
**RaycastHit2D hit = Physics2D.Raycast(transform.position, Camera.main.ScreenToWorldPoint (Input.mousePosition));
endPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition);
//ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (hit != null)
{
Debug.Log ("step 1 done");
Debug.Log (" |_hit.point = " + hit.point);
if (endPoint.x != hit.point.x && endPoint.y != hit.point.y)
{
endPoint.x = hit.point.x;
endPoint.y = hit.point.y;
Debug.Log (" |_newEndpoint = " + endPoint);
}
}**
Debug.Log ("endpoint = " + endPoint);
//make it so player can move
RB.isKinematic = false;
//get the mousepoint clicked position
endPoint.z = 0;
//normalize the position the player must reach
target = (endPoint - transform.position).normalized;
}
}
Im sorry, thought I could bold the code portion that i was using but the below snippet is what I am using Raycasthit2d for
RaycastHit2D hit = Physics2D.Raycast(transform.position, Camera.main.ScreenToWorldPoint (Input.mousePosition));
endPoint = Camera.main.ScreenToWorldPoint (Input.mousePosition);
//ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (hit != null)
{
Debug.Log ("step 1 done");
Debug.Log (" |_hit.point = " + hit.point);
if (endPoint.x != hit.point.x && endPoint.y != hit.point.y)
{
endPoint.x = hit.point.x;
endPoint.y = hit.point.y;
Debug.Log (" |_newEndpoint = " + endPoint);
}
}
Your answer
Follow this Question
Related Questions
Raycast doesn't stay in one place 0 Answers
Physics Raycast not working 1 Answer
Raycast shooting, child collider call and detection 0 Answers
About AI detecting a sound 1 Answer
Use raycast to change color 1 Answer