How to make my 2D character 'look' or flip in the direction he is moving? - c#

I'm a total newbie in Unity and I'm learning/making my first game, which will be a platformer. I want to get the movement perfect first. I've added a simple script that enables the player to move and jump.
Here it is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour{
public float jumpspeed = 5f;
public float speed = 5f;
Rigidbody2D rb;
GameObject character;
// Start is called before the first frame update
void Start()
{
}
void Awake(){
rb = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space)){
Jump();
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += move *Time.deltaTime * speed;
}
void Jump(){
rb.AddForce(new Vector2(0f, jumpspeed), ForceMode2D.Impulse);
}
}
Now, I want the character to face in the direction in which it moves. The png is facing to the right by default.
How can I do that? Also, can I make my movement script better?
Thanks in advance!

I typically do this using code like this based off a bool.
void FlipSprite()
{
isFacingRight = !isFacingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}

Related

Character doesn't change X axis orientation in Unity

Hello fellow programmers. I have an issue with my C# script.
I'm making a Unity 2D game, i imported my spritesheet and all, i programmed a way for my character to move on the X axis, it can now walk.
Then i tried to rotate it so it can face the direction he's walking... but it doesn't work, when I make it walk right, it's already facing right so it's fine, but when I make it go left, it just moonwalks to the left.
Here's my code for you to see how I wrote it : (Unity 2022.1.20f1)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KnightScript : MonoBehaviour
{
[SerializeField] float speed = 2f, jumpForce = 500f;
Rigidbody2D rb;
Animator anim;
[SerializeField] bool lookRight = true;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
float move = Input.GetAxis("Horizontal");
transform.Translate(Vector2.right * move * speed * Time.deltaTime);
anim.SetFloat("Speed", Mathf.Abs(move));
if(move < 0 && lookRight)
{
Flip();
}
else if(move < 0 && lookRight)
}
void Flip()
{
lookRight = !lookRight;
Vector2 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
I havent worked with unity for a while now but i think a better appraoch would be to get the Sprite from your GameObject and use the flipX() method like this:
GetComponent<SpriteRenderer>().flipX = true;

Rotate enemy character to see player character

I am making the enemy character to follow the player character.
In the FixedUpdate method the enemy character move toward the player character,
then in the Update method character rotates to the player character.
However, with this script, somehow enemy character is just nudging and gets stuck.
Where is the mistake, what's wrong???
public class enemy : MonoBehaviour
{
GameObject tObj;
private Vector3 latestPos;
public string targetObjectName;
public float speed = (float)1.0;
void Start()
{
tObj = GameObject.Find("player");
latestPos = transform.position;
}
void Update()
{
Vector3 diff = transform.position - latestPos;
latestPos = transform.position;
if (diff.magnitude > 0.01f)
{
transform.rotation = Quaternion.LookRotation(diff);
}
}
void FixedUpdate(){
Vector3 dir = (tObj.transform.position - this.transform.position).normalized;
float vx = dir.x * speed;
float vz = dir.z * speed;
this.transform.Translate((float)(vx / 50.0),0,(float)(vz / 50.0));
}
}
Use Package Manager "Standard Assets", Inside Unity put two FPSController one should be Player and the second can be Enemy.
I know this does not answers your question but its a faster way to ad Enemy.
AI Settings
Just remove the camera, Audio Source and First Person Controller Script as in image.
The Code for AI:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowAI : MonoBehaviour
{
public CharacterController _controller;
public Transform target;
public GameObject Player;
[SerializeField]
float _moveSpeed = 2.0f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update() {
Vector3 direction = target.position - transform.position;
direction = direction.normalized;
Vector3 velocity = direction * _moveSpeed;
_controller.Move(velocity * Time.deltaTime);
Vector3 lookVector = Player.transform.position - transform.position;
lookVector.y = transform.position.y;
Quaternion rot = Quaternion.LookRotation(lookVector);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, 1);
}
}

With what I should replace dirX for my bullets to shoot right and left

I am doing a 2d game and I want to know how I can make the bullets to shoot right and left . At this moment the bullets go just to the left , even if my player moves right. How I can make them shoot both sides or shoot just when they find an object tagged " enemy "
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class Character : MonoBehaviour
{
Rigidbody2D rb;
float dirX;
[SerializeField]
float moveSpeed = 5f, jumpForce = 400f, bulletSpeed = 500f;
Vector3 localScale;
public Transform barrel;
public Rigidbody2D bullet;
// Use this for initialization
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}
void FixedUpdate()
{
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
}
void Jump()
{
if (rb.velocity.y == 0)
rb.AddForce(Vector2.up * jumpForce);
}
void Fire()
{
var firedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
firedBullet.AddForce(barrel.up * bulletSpeed);
}
}
You're already accounting for the direction of the barrel. You just need to change the direction of the barrel when you move.
One way to do that is to just set that directly:
// Update is called once per frame
void Update()
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (dirX !=0)
{
barrel.up = Vector3.right * Mathf.Sign(dirX);
}
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}
If the barrel is a child of the player object, then changing the character's rotation so that the barrel's direction points in the correct direction will also work. There's not enough information in the question to know for sure but maybe using Quaternion.LookRotation to set the character's rotation like so would work:
// Update is called once per frame
void Update()
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (dirX !=0)
{
Vector3 newPlayerForward = Vector3.forward * Mathf.Sign(dirX);
transform.rotation = Quaternion.LookRotation(newPlayerForward, Vector3.up);
}
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}

Animation Starts but player won't move on key press in Unity

Me and 3 friends started working on game and while codding run into error that animation on player starts but it won't move. We are working in Unity(C#)
I already checked for names in Animator and code so it's not it.
Here is a code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float moveSpeed = 5f;
public Animator anim;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
Jump();
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f , 0f);
transform.position += movement * Time.deltaTime * moveSpeed;
if(Input.GetAxis("Horizontal") > 0){
anim.SetBool("isWalking", true);
}
else
{
anim.SetBool("isWalking", false);
}
}
void Jump(){
if (Input.GetButtonDown("Jump")){
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f,5f), ForceMode2D.Impulse);
}
}
}
It's 2D game if It matters
You could try to create the rigidbody2d in start(), then try
rigidbody.AddForce(Vector2(moveSpeed,0), ForceMode2D.Impulse);

Can't rotate and move at the same time

I'm currently developing an FPS shooter in Unity 3D. I'm fairly new to Unity and I've been having a bit of trouble with my player movement script. Individually everything seems to work, I can rotate and move the player freely, however when I try doing the two simultaneously my player seems to lock and won't rotate.
Sometimes jumping or moving to higher ground on the terrain seems to fix the issue, however I ran a few checks with gravity disabled, no colliders, and with the player well above ground, so the problem seems to be with the script. I've also done a bit of debugging and the Rotate() code does run, just the rotation amount doesn't seem to change.
Here is the player movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMov : MonoBehaviour
{
[SerializeField]
private Camera cam;
[SerializeField]
private float speed = 5f;
[SerializeField]
private float looksensitivity = 4f;
[Header("Camera View Lock:")]
[SerializeField] //min and max amount for looking up and down (degrees)
private float lowlock = 70f;
[SerializeField]
private float highlock = 85f;
private Rigidbody rb;
private float currentrotx; //used later for calculating relative rotation
public Vector3 velocity;
public Vector3 rotation; // rotates the player from side to side
public float camrotation; // rotates the camera up and down
public float jmpspe = 2000f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
CalcMovement();
CalcRotation();
Rotate();
}
void FixedUpdate()
{
Move();
}
private void CalcRotation()
{
float yrot = Input.GetAxisRaw("Mouse X"); //around x axis
rotation = new Vector3(0f, yrot, 0f) * looksensitivity;
float xrot = Input.GetAxisRaw("Mouse Y"); //around y axis
camrotation = xrot * looksensitivity;
}
private void CalcMovement()
{
float xmov = Input.GetAxisRaw("Horizontal");
float zmov = Input.GetAxisRaw("Vertical");
Vector3 movhor = transform.right * xmov;
Vector3 movver = transform.forward * zmov;
velocity = (movhor + movver).normalized * speed;
}
void Move()
{
//move
if (velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
//jump
if (Input.GetKeyDown(KeyCode.Space))
{
//add double jump limit later!
rb.AddForce(0, jmpspe * Time.deltaTime, 0, ForceMode.Impulse);
}
}
void Rotate()
{
//looking side to side
rb.MoveRotation(rb.rotation * Quaternion.Euler(rotation));
// camera looking up and down
currentrotx -= camrotation;
currentrotx = Mathf.Clamp(currentrotx, -lowlock, highlock);
cam.transform.localEulerAngles = new Vector3(currentrotx, 0, 0);
}
}
Here are the relevant components attached to my player:
(The player has a couple more components attached but I ran tests without them and the problem still occurs)
Like I said I'm a bit of a unity novice, so i'm sure I missed something small but I just can't seem to place my finger on it, I've been stuck on this for a while so any help is much appreciated.
SOLVED:
It seems the problem I had was because I was running the scene from my laptop and not a desktop which I assume is what the Unity input was built for.

Categories