trying to move child object on raycast check, object not moving
Hi, so i have a dash attack in my game and the dash distance is determined by a child game object X distance in front of the player object.. im trying to use a raycast hit to tell the dash object to move closer to the player object if it collides with a wall, i feel like im doing everything right but the result i want is not being achieved, the bool for collision with the wall is returning true and i have all my layers set the way theyre supposed to etc. the dash pos is just an empty game object.
if anyone has an alternative to solving this problem im all for it.. Thanks.
private GameObject playerObject;
private GameObject dashLocation;
private Transform Player;
//dashing
public float dashSpeed;
bool dashing;
public bool wallhit;
void Awake()
{
Player = this.GetComponent<Transform>();
playerObject = GameObject.FindGameObjectWithTag("Player");
dashPos = playerObject.transform.FindChild("dashPos");
dashLocation = GameObject.FindGameObjectWithTag("dashPos");
}
void FixedUpdate()
{
Raycasting();
}
void Raycasting()
{
float wallDistance;
float start = Player.transform.position.x;
float end = dashPos.transform.position.x;
Vector2 rayOrigin = new Vector2(Player.transform.position.x, Player.transform.position.y);
Vector2 rayEnd = new Vector2(dashPos.transform.position.x, dashPos.transform.position.y);
Vector2 rayDirection = new Vector2(Player.transform.localScale.x, 0);
RaycastHit2D hit = Physics2D.Raycast(rayOrigin, rayDirection, 2.1f);
//Debug.DrawLine(rayOrigin, rayEnd, Color.green);
wallhit = Physics2D.Linecast(rayOrigin, rayEnd, 1 << LayerMask.NameToLayer("Walls"));
//checks for walls, if wall is closer than dash position, move dash position closer to player
if ((hit.collider.tag == "Walls"))
{
wallDistance = hit.transform.position.x;
if (end >= wallDistance)
{
dashLocation.transform.position = new Vector2(wallDistance - 1f, Player.transform.position.y);
}
}
}
Answer by je66_b · Apr 05, 2017 at 06:40 PM
solved using an alternate method. removed child game object and just used distance.
private void rayCasting()
{
rayOrigin = new Vector2(transform.position.x, transform.position.y);
rayDirection = new Vector2(transform.localScale.x, 0);
//the change i made
rayCastDistance = 2.1f;
//
hit = Physics2D.Raycast(rayOrigin, rayDirection, rayCastDistance, 1 << LayerMask.NameToLayer("Walls"));
if (hit)
{
maxDistance = hit.distance;
}
if (!hit)
{
maxDistance = rayCastDistance;
}
}
Your answer
Follow this Question
Related Questions
Issue with character movement and collision using Physics2D.Raycast. 0 Answers
I can't get Raycasting in 2D to work, what am I missing? 1 Answer
Allow raycast to skip an object with rigidbody 0 Answers
Is there any way how to do raycasts like this? 0 Answers
two boxCasts casted from same point give different results 0 Answers