This is a 2D game, and I’m trying to replace this code to work with a controller instead of using the mouse position.
So I have an issue where my character is supposed to move the flashlight in the direction of the right stick, and when the person stops moving the right stick it should keep its last position, but instead it always reverts back to the vector(0,0,0) (or straight down). This seemed fairly straightforward issue, my answer was storing the last known input not at 0, then saving that in a temp variable, but it still isn’t working. Any ideas? Thanks!
private void turnFlashlight()
{
Vector3 Target = new Vector3(Input.GetAxis("rHorizontal")*360,-Input.GetAxis("rVertical")*360, 0f);
Vector3 Temp = new Vector3(0f, 0f, 0.0f);
if((Target.x != 0) && (Target.y != 0)){
Temp = Target;
}
if (!CharacterSettings.paused)
{
flashlight.transform.LookAt(Temp);
}
}
Instead of setting the flashlight directly to the position of the axis, you should add the stick’s values to the direction each frame.
You might consider refactoring it so you work with euler angles instead of using LookAt, but I don’t know the actual implications of your game or how else you’re using the look target, so it’s not my call.
Something along these lines might be suitable:
[SerializeField] float m_flashlightLookSpeed = 1.0f;
Vector3 m_lookPosition;
[SerializeField, Space] float m_lookRangeX;
[SerializeField] float m_lookRangeY;
private void turnFlashlight( ) // Called every Update()
{
Vector3 Offset = new Vector3( Input.GetAxis( "rHorizontal" ) * 360, -Input.GetAxis( "rVertical" ) * 360, 0f );
m_lookPosition.x += Mathf.Clamp( Offset.x * m_flashlightLookSpeed * Time.deltaTime, -m_lookRangeX, m_lookRangeX );
m_lookPosition.y += Mathf.Clamp( Offset.y * m_flashlightLookSpeed * Time.deltaTime, -m_lookRangeY, m_lookRangeY );
if ( !CharacterSettings.paused )
flashlight.transform.LookAt( m_lookPosition );
}
Edit 1: Oops! I just re-read the question, and I just noticed you said it’s a 2D game. I’m sorry I missed that. You’re on the right lines with trying to keep track of the last position, but you need to store it earlier, before the stick is fully centered.
[SerializeField] float m_deadzone = 0.5f;
// In the method
if ( Target.sqrMagnitude > m_deadzone * m_deadzone )
Temp = Target;
Edit 2:
I see. It’s pointing down because if it’s within the deadzone, temp becomes 0,0,0. You should hang onto the last viable look position:
[SerializeField] float m_deadzone = 0.5f;
Vector3 m_lookTarget = Vector3.zero; // Hang onto it here, between method calls
// In the method
if ( Target.sqrMagnitude > m_deadzone * m_deadzone )
m_lookTarget = Target;
// Don't set it to 0 if inside the deadzone
if ( !CharacterSettings.paused )
flashlight.transform.LookAt( m_lookPosition );