마우스 방향으로 공격을 하고 싶습니다.
609
작성한 질문수 2
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); //좌우방향
}
코드 관련 질문
0
21
2
섹션7 수업자료 업로드 부탁드립니다.
0
21
2
Dictionary Key를 int에서 string으로 변경한 이유에 대한 문의
0
18
1
프로젝트 질문 문의
0
45
1
UI 기능 관련 질문이 있습니다!
0
37
2
03-01 (16. CharacterController)
0
31
2
TLS 질문드립니다.
0
43
2
Task 구현 28:36 Equals 에서 잘 모르는 부분이 있습니다.
0
27
2
SpinLock과 컨텍스트스위칭에 대해 질문 남겨요.
0
46
2
픽셀 좌표 스크린 좌표
0
33
0
Locomotion랑 Turn 이 꼭 부모 자식 관계일 필요가 있나요?
0
25
1
Rider대신 VS를 써도 괜찮나요?
0
116
2
Claude Code Pro구독하고 있는 상태에서 크레딧 결제, 사용문의
0
217
2
자꾸만 번거롭게 해서 죄송합니다.....
0
69
2
이거 후속 강의는 없는 건가요? ㅠㅠ
0
76
2
이거 후속 강의는 없는 건가요? ㅠㅠ
0
52
1
공격후에 미끄러지는 오류
0
223
1
스크립트 오류 관련
0
287
2
강좌가 마음에 드는데 심화과정 만드실 계획 있으신가요?
1
255
1
계단에서 착지시 문제점!
0
263
1
4번째 강의 질문
0
232
2
강의 질문드립니다.
0
395
4
엣지콜라이더설치후 폴리싱 관련된 부분 질문드립니다.
0
427
2
강의 순서가 이상해 질문 올립니다~
1
353
2





