playMaker

Author Topic: XY Angle between Two Points  (Read 3106 times)

iloveaphextwin

  • Playmaker Newbie
  • *
  • Posts: 8
    • View Profile
XY Angle between Two Points
« on: August 18, 2013, 05:47:52 AM »
Hi there,

I was going crazy trying to calculate the angle between two game objects using only x and y. So I made a simple action that works like most 2d programs. Math.atan to get the angle. Works perfectly for me so hope it can help someone.

Code: [Select]
using UnityEngine;
using HutongGames.PlayMaker;

[ActionCategory(ActionCategory.Transform)]
[Tooltip("XY angle")]

public class xyAngleBetweenTwoPoints : FsmStateAction {
[RequiredField]
[Tooltip("The game object whose forward axis we measure from. If the target is dead ahead the angle will be 0.")]
public FsmOwnerDefault gameObject;

[Tooltip("The target object to measure the angle to. Or use target position.")]
public FsmGameObject targetObject;

[RequiredField]
[UIHint(UIHint.Variable)]
[Tooltip("Store the angle in a float variable.")]
public FsmFloat storeAngle;

[Tooltip("Repeat every frame.")]
public bool everyFrame;

public override void Reset() {
gameObject = null;
targetObject = null;
storeAngle = null;
everyFrame = false;
}

public override void OnLateUpdate() {
DoGetAngleToTarget();

if (!everyFrame) {
Finish();
}
}

void DoGetAngleToTarget() {
var go = Fsm.GetOwnerDefaultTarget(gameObject);

if (go == null) {
return;
}

var goTarget = targetObject.Value;

if (goTarget == null) {
return;
}

float xDiff = goTarget.transform.position.x - go.transform.position.x;
float yDiff = goTarget.transform.position.y - go.transform.position.y;
storeAngle.Value =  Mathf.Atan2(yDiff, xDiff) * (180 / Mathf.PI);

}

}

Thanks

Will

jeanfabre

  • Administrator
  • Hero Member
  • *****
  • Posts: 14684
  • Official Playmaker Support
    • View Profile
Re: XY Angle between Two Points
« Reply #1 on: August 19, 2013, 12:33:16 AM »
Hi,

 Also, I made a package on the wiki to work with angles. You may find in there some useful actions as well.

https://hutonggames.fogbugz.com/default.asp?W971

bye,

Jean