반응형

유도 미사일을 만들어 보자.

 

Square(Target)와 Capsule(Missile) 스프라이트를 생성한다.

 

Missile에 Rigidbody2D(Gravity Scale = 0)와 스크립트를 추가한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
[RequireComponent(typeof(Rigidbody2D))]
public class Guide : MonoBehaviour
{
    public Transform target;
    private Rigidbody2D rb;
 
    public float speed = 5.0f;
    public float rotateSpeed = 200.0f;
 
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
 
    private void FixedUpdate()
    {
        Vector2 direction = (Vector2)target.position - rb.position;
        direction.Normalize();
 
        float rotateAmount = Vector3.Cross(direction, transform.up).z;
        rb.angularVelocity = -rotateAmount * rotateSpeed;
 
        rb.velocity = transform.up * speed;
    }
}
 

 

스크립트를 작성한다.

 

스크립트 Target 변수에 Target 오브젝트(Square)를 선택한다.

 

 

플레이 하면 미사일이 목표를 향해 날아간다.

 

반응형
Posted by J-sean
: