- Home /
 
 
               Question by 
               MontigorJ · Apr 07, 2020 at 02:56 PM · 
                rotationgameobjectdirectionrotate object  
              
 
              Change gameObject rotation towards reflection direction.
Hi, i am making a game where you shoot an arrow which can reflect from the walls. I did a ricochet code but can't figure out how to make arrow always face its direction. I tried many different things but did not find a solution. Can somebody help me with that?
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class arrowScript : MonoBehaviour { public float speed = 50f; public Rigidbody2D rb; public Vector3 arrowDir; //private float arrowAngle;
 private void Start()
 {
     arrowDir = bowScript.dir;
     arrowDir.z = 0;
     rb.velocity = arrowDir.normalized * speed;
    // transform.Rotate(0f,0f,arrowAngle);
 }
 void OnCollisionEnter2D(Collision2D other)
 {
     if(other.gameObject.CompareTag("Block"))
     {
         Vector2 wallNormal = other.contacts[0].normal;
         arrowDir = Vector2.Reflect(rb.velocity, wallNormal).normalized;
         //arrowAngle = Vector2.Angle(arrowDir, wallNormal);
         rb.velocity = (arrowDir * speed);
        // transform.Rotate(0f, 0f, arrowAngle);
        // Debug.Log(arrowAngle);
     }
 }
 
               }
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by MontigorJ · Jul 05, 2020 at 01:50 PM
Okay, i have solved this thing a while ago, so decided to post my way on rotation. Maybe somebody will find it useful.
      Vector2 wallNormal = other.contacts[0].normal;
      arrowDir = Vector2.Reflect(rb.velocity, wallNormal).normalized;
     rb.velocity = (arrowDir * speed);
     Debug.Log("arrowdir " + arrowDir);
     float arrowAngle = Mathf.Atan2(arrowDir.y, arrowDir.x) * Mathf.Rad2Deg;
     Quaternion q = Quaternion.AngleAxis(arrowAngle, Vector3.forward);
     transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime*100f);
 
              Your answer