• 카테고리

    질문 & 답변
  • 세부 분야

    게임 프로그래밍

  • 해결 여부

    미해결

마우스 방향으로 공격을 하고 싶습니다.

23.08.24 14:51 작성 조회수 270

0

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class VPlayer : MonoBehaviour

{

#region 변수 모음

public float speed;

public float power;

public Vector3 direction;

Animator pAnimator;

Rigidbody2D pRig2D;

SpriteRenderer sp;

GrapplingHook grappling; // GrapplingHook C# 코드 불러오기

#endregion

#region 점프 변수 모음

[Header("Jump System")]

[SerializeField] float jumpUp;

[SerializeField] float fallMultiplier;

[SerializeField] float jumpTime;

[SerializeField] float jumpMuitiplier;

Vector2 vecGravity;

bool isJumping;

float JumpCounter;

#endregion

#region 벽 점프 변수 모음

[Header("Wall Jump System")]

public Transform wallChk;

public float wallchkDistance;

public LayerMask wLayer;

bool isWall;

public float slidingSpeed;

public float wallJumpPower;

public bool isWallJump;

float isRight = 1;

#endregion

#region 공격 관련 변수

[Header("Attack System")]

public GameObject Vslash; // 공격 모션

#region 마우스 관련 변수 모음

Vector2 MousePos;

Vector3 dir;

float angle;

Vector3 dirNo;

#endregion

#endregion

#region 초기화

void Start()

{

pAnimator = GetComponent<Animator>();

pRig2D = GetComponent<Rigidbody2D>();

direction = Vector2.zero;

sp = GetComponent<SpriteRenderer>();

grappling = GetComponent<GrapplingHook>();

vecGravity = new Vector2(0, -Physics2D.gravity.y);

}

#endregion

void Update()

{

if (!isWallJump)

{

KeyInput();

Move();

mousePos();

}

#region 점프 키 누름

if (Input.GetKeyDown(KeyCode.W))

{

if (pAnimator.GetBool("Jump") == false)

{

Jump();

isJumping = true;

JumpCounter = 0;

pAnimator.SetBool("Jump", true);

//JumpDust();

}

}

#endregion

#region 점프 후 떨어질 때 가속

if (pRig2D.velocity.y < 0)

{

pRig2D.velocity -= vecGravity fallMultiplier Time.deltaTime;

}

#endregion

#region 점프 키를 꾹 눌렀을 시 더 높이 점프

if (pRig2D.velocity.y > 0 && isJumping)

{

JumpCounter += Time.deltaTime;

if (JumpCounter > jumpTime) isJumping = false;

pRig2D.velocity += vecGravity jumpMuitiplier Time.deltaTime;

}

if (Input.GetKeyUp(KeyCode.W))

{

isJumping = false;

}

#endregion

#region 벽인지 체크

isWall = Physics2D.Raycast(wallChk.position, Vector2.right * isRight, wallchkDistance, wLayer);

pAnimator.SetBool("Wall", isWall);

#endregion

#region 벽타기

if (isWall)

{

isWallJump = false;

pRig2D.velocity = new Vector2(pRig2D.velocity.x, pRig2D.velocity.y * slidingSpeed);

#region 벽을 잡고 있는 상태에서 점프

if (Input.GetKeyDown(KeyCode.W))

{

isWallJump = true;

//벽점프 먼지

//GameObject go = Instantiate(walldust, transform.position + new Vector3(0.6f * isRight, -0.32f, 0), Quaternion.identity);

//go.GetComponent<SpriteRenderer>().flipX = sp.flipX;

Invoke("FreezeX", 0.3f);

pRig2D.velocity = new Vector2(-isRight wallJumpPower, 0.9f wallJumpPower);

sp.flipX = sp.flipX == false ? true : false;

isRight = -isRight;

}

#endregion

}

#endregion

}

private void FixedUpdate()

{

#region 바닥 감지 레이저

Debug.DrawRay(pRig2D.position, Vector3.down, new Color(0, 1, 0));

RaycastHit2D rayHit = Physics2D.Raycast(pRig2D.position, Vector3.down, 0.8f, LayerMask.GetMask("Ground"));

#endregion

#region Ground를 감지할 때

if (pRig2D.velocity.y < 0)

{

if (rayHit.collider != null)

{

if (rayHit.distance < 0.6f)

{

pAnimator.SetBool("Jump", false);

}

}

#region 6-2. 떨어질 때의 감지 방식

else

{

if (!isWall)

{

//그냥 떨어지는 중 fall

pAnimator.SetBool("Jump", true);

}

else

{

//벽타기

pAnimator.SetBool("Wall", true);

}

}

#endregion

}

#endregion

}

#region 키 입력

void KeyInput()

{

direction.x = Input.GetAxisRaw("Horizontal");

#region 왼쪽

if (direction.x < 0)

{

//left

sp.flipX = true;

//점프벽잡기 방향

isRight = -1;

pAnimator.SetBool("Run", true);

}

#endregion

#region 오른쪽

else if (direction.x > 0)

{

//right

sp.flipX = false;

//점프벽잡기 방향

isRight = 1;

pAnimator.SetBool("Run", true);

}

#endregion

#region Idle 상태

else if (direction.x == 0)

{

pAnimator.SetBool("Run", false);

}

#endregion

#region 공격 버튼

if (Input.GetMouseButtonDown(0))

{

pAnimator.SetTrigger("Attack");

//Instantiate(hit_lazer, transform.position, Quaternion.identity);

}

#endregion

}

#endregion

#region 이동

void Move()

{

if (direction.x != 0)

{

if (grappling.isAttach)

{

pRig2D.AddForce(new Vector2(direction.x * speed, 0)); //로프 이동

}

else

pRig2D.velocity = new Vector2(direction.x * speed, pRig2D.velocity.y); //보통 이동

}

}

#endregion

#region 점프

public void Jump()

{

pRig2D.velocity = new Vector2(pRig2D.velocity.x, jumpUp);

}

#endregion

#region 마우스 방향

public void mousePos()

{

Transform tr = GetComponent<Transform>();

MousePos = Input.mousePosition;

MousePos = Camera.main.ScreenToWorldPoint(MousePos);

Vector3 Pos = new Vector3(MousePos.x, MousePos.y, 0);

dir = Pos - tr.position;

// 바라보는 각도 구하기

angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;

}

#endregion

#region 공격 이펙트

public void AttSlash()

{

pRig2D.AddForce(dir.normalized * power, ForceMode2D.Impulse);

GameObject go = Instantiate(Vslash, transform.position, Quaternion.identity);

if (dir.x <= 0)

{

sp.flipX = true;

}

else

{

sp.flipX = false;

}

}

#endregion

void FreezeX()

{

isWallJump = false;

}

}

 

마우스 방향 값을 이용해 좌클릭을 할 때 마우스 방향으로 공격을 하는 코드를 짜고 있는 데, 이동을 velocity로 해서 그런지 idle 상태 run 상태에서 좌클릭을 누르면 공격 모션만 마우스 방향으로만 가고 플레이어는 마우스 방향으로 앞으로 대쉬하지 않습니다. 이때는 어떻게 처리해야 하는 지 알려주시면 감사하겠습니다.

 

코루틴도 써봤지만 답이 안나와서 올립니다.

답변 1

답변을 작성해보세요.

0

해당 코드에서 마우스방향을 구하는 dir 방향으로 속도값을 주면 가능하지 않을까 생각됩니다.

리지드바디같은경우에는 addForce또는 velocity를 통해서 값을 주시면됩니다.

리지드바디.velocity 에 방향과 속도를 곱한값을 주시면되지 않을까 생각합니다.

 

x쪽 대시 부분을 구현한영상을 한번 참고해보세요.

 

https://www.youtube.com/watch?v=LttTs_W2DFY

 

//대시스피드 X쪽 * 방향

player.SetVelocity(player.dashSpeed * player.dashDir, 0);

 

 

public void SetVelocity(float xVelocity, float yVelocity)

{

rb.velocity = new Vector2(_xVelocity, _yVelocity);

FlipController(_xVelocity); //좌우방향

}