You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.6 KiB
53 lines
1.6 KiB
3 years ago
|
using System;
|
||
|
using System.Collections;
|
||
|
using System.Collections.Generic;
|
||
|
using UnityEngine;
|
||
|
using UnityEngine.InputSystem;
|
||
|
|
||
|
public class PlayerController : MonoBehaviour
|
||
|
{
|
||
|
private Rigidbody2D rb;
|
||
|
private SpriteRenderer sr;
|
||
|
private Camera main;
|
||
|
|
||
|
//Input
|
||
|
private PlayerInput input;
|
||
|
private InputAction moveAction;
|
||
|
private InputAction fightAction;
|
||
|
|
||
|
private Vector2 moveDirection;
|
||
|
private float moveSpeed = 5f;
|
||
|
|
||
|
|
||
|
// Start is called before the first frame update
|
||
|
private void Awake()
|
||
|
{
|
||
|
rb = this.gameObject.GetComponent<Rigidbody2D>();
|
||
|
input = this.gameObject.GetComponent<PlayerInput>();
|
||
|
moveAction = input.actions["Move"];
|
||
|
fightAction = input.actions["Fight"];
|
||
|
|
||
|
//Input events
|
||
|
moveAction.performed += ctx => Move(ctx.ReadValue<Vector2>());
|
||
|
moveAction.canceled += ctx => Move(Vector2.zero);
|
||
|
main = Camera.main;
|
||
|
}
|
||
|
|
||
|
private void FixedUpdate()
|
||
|
{
|
||
|
//Update move direction
|
||
|
rb.MovePosition(rb.position + moveDirection * moveSpeed * Time.fixedDeltaTime);
|
||
|
}
|
||
|
|
||
|
private void Update()
|
||
|
{
|
||
|
//Update the sprite direction based on mouse position
|
||
|
Vector2 mousePos = main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
|
||
|
Vector2 direction = mousePos - (Vector2)transform.position;
|
||
|
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
|
||
|
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
|
||
|
}
|
||
|
|
||
|
//update the move direction
|
||
|
void Move(Vector2 direction) => moveDirection = direction;
|
||
|
}
|