- Home /
sidescroller: flipping sides of player based on direction (C#)
I have a simple side-scroller with a capsule player and a projectile spawn on the right side of the player. The game works fine, allowing me to shoot projectiles to the right. The only problem: I can only shoot in one direction. How can I make the player face the direction it is moving, so I can fire projectiles both left and right. This is my current script so far that is attached to my player:
using UnityEngine;
public class Player : MonoBehaviour // The class was missing, I improvised (Berenger)
{
public float moveSpeed = 10f;
public float rotateSpeed = 5f;
// Update is called once per frame
void Update ()
{
float moveForward = moveSpeed * Time.smoothDeltaTime * Input.GetAxis("Vertical");
float moveleft = moveSpeed * Time.smoothDeltaTime * Input.GetAxis("Horizontal");
float rotate = rotateSpeed * Time.smoothDeltaTime * Input.GetAxis("Horizontal");
transform.Translate(Vector3.forward * moveForward);
transform.Translate(Vector3.back * moveleft);
if(Input.GetKeyDown(KeyCode.Space))
rigidbody.AddForce(Vector3.up * 500);
}
}
Answer by Berenger · Jun 25, 2012 at 02:53 AM
You've got several details you need to improve.
You need to move the character only whe there is an input. To do so, you check the value of the axes.
float h = Input.GetAxis( "Horizontal" );
// Apparently, product cost less than Abs, even if you would need hundreds of player
// to see a difference. And it takes less letters to write !
// PS : This is totally empirical
if( h*h > Mathf.Epsilon ) // Use of epsilon because of floats
{
Vector3 movement = new Vector3( h * Time.deltaTime, 0f, 0f );
// Apply movement
}
And your character has a rigidbody, you should use it to move or you won't have any collisions.
About the facing, you can use transform.LookAt, Quaternion.LOokRotation or transform.forward = ...
Your answer
Follow this Question
Related Questions
2d side scroller projectile/firing weapon script help needed. 1 Answer
Shoot second cell in 2d 0 Answers
Implementing a "Fire Mode" in 2D 1 Answer
2D Shooting & Direction 1 Answer