Question by
$$anonymous$$ · May 05, 2017 at 01:05 PM ·
c#rotationquaternionraycasthit2d
Why raycast2d not work?
I made a spaceship, which should detect the obstacles on its way by Raycast2D and avoid them automatically.
Pls see my update() codes:
void Update()
{
//right
Debug.DrawLine(new Vector2(transform.position.x, transform.position.y + transform.localScale.y), new Vector2((transform.position + transform.right * (sensorLen + transform.localScale.y)).x, transform.position.y + transform.localScale.y), Color.green);
//left
Debug.DrawLine(new Vector2(transform.position.x, transform.position.y - transform.localScale.y), new Vector2((transform.position + transform.right * (sensorLen + transform.localScale.y)).x, transform.position.y - transform.localScale.y), Color.red);
//these are raycast!
RaycastHit2D rightHit = Physics2D.Linecast(new Vector2(transform.position.x, transform.position.y + transform.localScale.y), new Vector2((transform.position + transform.right * (sensorLen + transform.localScale.y)).x, transform.position.y + transform.localScale.y));
RaycastHit2D leftHit = Physics2D.Linecast(new Vector2(transform.position.x, transform.position.y - transform.localScale.y), new Vector2((transform.position + transform.right * (sensorLen + transform.localScale.y)).x, transform.position.y - transform.localScale.y));
//right sensor
if( rightHit )
{
if( rightHit.collider != col )
{
//find the hit obstacle
Transform hitTrans = basHit.transform;
Vector2 direction = new Vector2(hitTrans.position.x, hitTrans.position.y - hitTrans.localScale.y) - new Vector2(transform.position.x,transform.position.y);
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, turnSpeed * Time.deltaTime);
Debug.Log("hit right");
}
}
}
However, when I ran the codes, I found that the ship will not turn until it really hit on the obstacle---the raycast not effects at all. Also, until the ship really hit on the obstacle, the "hit right" would be shown in the console.
I don't know why. I changed many ways to rotate, nothing worked. Please help me! Thanks.
Comment
Your answer
Follow this Question
Related Questions
How to rotate a camera slowly along a tween? 1 Answer
Grabbing the Relative eulerAngles.y of a Rotation 1 Answer
Smooth 90 degree rotation on keypress 3 Answers
Clamp a rotation in unity 0 Answers
-= Time.deltaTime 1 Answer