- Home /
How do i get a attack offset of the player at a fixed distance in 2D?
Goal: I am trying to create an attack towards the mouse click with an offset of the player. What works: instantiates the object at the correct angle towards the mouse click. Whats not working: currently the object is spawned close to the mouse click and not offset.
How can i get it to offset it a fixed distance away from the character while still keeping its angle?
 public IEnumerator Attack()
 {
     Vector3 mPos = Input.mousePosition;
     mPos.z = Camera.main.nearClipPlane;
     Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mPos);
     float angle_ = (Mathf.Atan2(transform.position.y - worldPosition.y, transform.position.x - 
     worldPosition.x) * Mathf.Rad2Deg);
     float trueAngle_;
     if (angle_ < 0)
         trueAngle_ = UnwrapAngle(angle);
     else
         trueAngle_ = WrapAngle(angle);
     Vector2 cPos = new Vector2(transform.position.x, transform.position.y);
     Vector2 dirVector = new Vector2(worldPosition.x + cPos.x, worldPosition.y + cPos.y);
     GameObject swing = Instantiate(slash, dirVector, Quaternion.AngleAxis(trueAngle_ + 90, Vector3.forward)) as GameObject;
     yield return new WaitForSeconds(.317f);
     Destroy(swing);
 }
Answer by FlaSh-G · Mar 31, 2020 at 08:45 PM
Instead of trigonometry, use vector math - it's much easier to use and will do the job just fine :)
 Vector3 mPos = Input.mousePosition;
 mPos.z = Camera.main.nearClipPlane;
 Vector3 worldPosition = Camera.main.ScreenToWorldPoint(mPos);
 
 Vector3 direction = worldPosition - transform.position;
 Vector3 result = transform.position + direction.normalized * distance;
Your answer
 
 
             Follow this Question
Related Questions
Instantiate Object in direction from another 1 Answer
Infinity runner - best way to spawn board in runtime. 0 Answers
When flipping player, instantiated objects spawn on different spot. 2D shooting 0 Answers
Instantiated object won't move! 1 Answer
OnTriggerEnter, called on both instantiated objects 2 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                