반응형

2022.09.17 - [Electronics] - 직류 전원 공급 장치 DC Power Supply

위 링크에서 LTSpice로 시뮬레이션 한 DC Power Supply를 PSpice로 시뮬레이션 해 보자.

 

위 그림처럼 구성한다.

● Power: VSIN으로 추가한다. Serial Resistance로 R1(0.001Ω)도 추가해야 한다.

● Transformer: L로 추가한다. 두 개(L1, L2)를 추가하고 K-Linear를 추가해서 우클릭 - Edit Part - Part Properties - L1에 L1, L2에 L2를 입력한다.

 

시뮬레이션 하면 약간 거친 그래프가 표시된다. 좀 더 부드러운 곡선으로 만들어 보자.

 

PSpice - Edit Simulation Profile - Transient options - Maximum Step Size 를 0.1m(or 더 작은 수)으로 변경한다.

 

부드러운 곡선으로 표시된다.

 

 

PSpice는 Transformer를 좀 더 간단히 만들 수 있다.

● XFRM_Linear로 추가하고 우클릭 - Edit Part - Part Properties - L1 VALUE에 2200µH, L2 VALUE에 1µH를 입력한다.

 

결과는 위와 같다.

 

완벽한 직류 5V를 공급하기 위해 LM7805를 추가한다.

● Transformer: L2 VALUE는 3µH로 수정한다. 1µH로 출력되는 전압은 너무 작아 LM7805로 제대로 정류할 수 없다.

● C2: LM7805 OUT에 0.1µF Capacitor를 추가 연결한다.

 

깨끗한 5VDC 전압이 출력된다.

 

반응형
Posted by J-sean
:
반응형

ParallaxBackground와 ParallaxLayer를 이용해 배경 화면을 자연스럽게 스크롤 해 보자.

 

Project Settings - Rendering - Textures - Canvas Textures - Default Texture Filter - Nearest 를 선택한다.

 

위와 같이 씬을 구성한다.

● ParallaxBackground - 두 개의 ParallaxLayer를 자식 노드로 생성하고 스크립트를 추가한다.

● ParallaxLayer - 각각 Sprite2D를 자식 노드로 생성한다.

● Sprite2D - 배경 화면을 Texture로 지정한다.

 

background_layer_1.png
0.01MB
background_layer_2.png
0.01MB

 

두 개의 ParallaxLayer 모두 Motion - Mirroring - X 속성을 스프라이트 크기에 맞게 지정한다.

수평으로 스크롤 하는 경우 X 속성을 지정하지만 수직이라면 Y 속성을 지정한다.

 

1
2
3
4
5
6
7
8
9
10
11
using Godot;
 
public partial class BackgroundScript : ParallaxBackground
{
    public int ScrollingSpeed = 100;
 
    public override void _Process(double delta)
    {
        ScrollOffset -= new Vector2(ScrollingSpeed * (float)delta, 0);
    }
}
 

 

ParallaxBackground 스크립트를 작성한다.

 

 

두 배경이 같은 속도로 이동한다.

 

멀리 있는 배경(ParallaxLayer)의 Motion - Scale 속성을 0.5로 지정한다.

 

멀리 있는 배경이 느리게 이동한다.

 

※ 참고

ParallaxBackground

ParallaxLayer

 

반응형
Posted by J-sean
:
반응형

PSpice로 시뮬레이션 하면 전류 값이 음수로 나오는 경우가 있다.

 

R7 저항의 플러스 핀을 찍고 전류 값을 시뮬레이션 해 보자.

 

양수 값으로 제대로 표현된다.

 

이번엔 마이너스 핀에 찍고 시뮬레이션 해 보자.

 

전류 값이 음수로 표현된다.

 

 

측정 위치가 플러스 인지 마이너스 인지에 따라서 부호가 바뀌는 거 같지만 다른 조건이 하나 더 있다. 1번 핀이 플러스 쪽에 연결되어야 한다. 핀 번호를 확인해보자.

 

저항을 우클릭하고 Edit Part를 선택한다.

 

Pin Number Visible을 선택하고 저장한다.

 

Pin Number가 표시된다.

시뮬레이션 결과에 전류 값이 음수로 나오거나 양수로 나오더라도 Legend에 -I(RX) 등으로 표시된다면 측정 위치와 핀 번호를 확인해 보자.

 

반응형
Posted by J-sean
:
반응형

기본적인 파티클 시스템 사용.

 

GPUParticles2D를 추가하고 Process Material에 ParticleProcessMaterial을 생성한다.

 

확대해보면 파티클이 생성되고 있다.

 

눈이 내리는 효과를 만들어 보자.

 

Emission Shape과 Gravity 속성을 위와 같이 변경한다.

 

Turbulence, Time - Lifetime 속성을 위와 같이 변경한다.

 

 

자연스럽게 눈이 내린다.

 

이번엔 비가 내리는 효과를 만들어 보자.

 

Direction, Gravity, Initial Velocity 속성을 위와 같이 변경한다.

 

Turbulence를 비활성화하고 Trails 속성을 활성화 하고 Lifetime을 적장히 조절한다.

 

비가 내린다.

 

 

Emission Mask를 사용해 특정 영역에서 파티클을 생성해 보자.

 

파티클 노드를 선택하고 GPUParticles2D - Load Emission Mask를 선택한다.

 

letter.png
0.01MB

 

마스크로 사용할 이미지를 선택한다.

 

Solid Pixels를 선택하고 OK를 클릭한다.

 

Amount, Direction, Initial Velocity 속성을 조절한다.

 

 

Turbulence, Time - Lifetime 속성을 조절한다.

 

Solid Pixels

 

Border Pixels

 

Directed Border Pixels

 

 

Color, Hue Variation 속성을 조절한다.

 

 

Texture를 지정하고 그에 맞게 Scale 속성을 설정한다.

 

flare-lens.png
0.31MB

 

 

※ 참고

2D particle Systems

 

반응형
Posted by J-sean
:
반응형

2D 네비게이션 기본 사용법

 

2D 네비게이션을 사용하기 위해 세팅한다.

● NavigationRegion2D - Navigation Polygon을 생성하고 NavigationAgent2D가 이동 가능한 공간을 적당히 그린다.

● CharacterBody2D - 스크립트를 생성한다.

   Sprite2D - 스프라이트 사이즈를 적당히 조절한다.

   CollisionShape2D - 스프라이트 사이즈에 맞게 적당히 조절한다.

   NavigationAgent2D - Debug - Enabled - On 체크한다.

 

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using Godot;
 
public partial class Nav : CharacterBody2D
{
    public float movement_speed = 300.0f;
    public Vector2 movement_target_position = new Vector2(950500);
    public NavigationAgent2D navigation_agent;
 
    public override void _Ready()
    {
        navigation_agent = GetNode<NavigationAgent2D>("NavigationAgent2D");
 
        // These values need to be adjusted for the actor's speed
        // and the navigation layout.
        navigation_agent.PathDesiredDistance = 4.0f;
        navigation_agent.TargetDesiredDistance = 4.0f;
 
        // Make sure to not await during _ready.
        CallDeferred("actor_setup");
        // Calls the method on the object during idle time. Always returns null,
        // not the method's result.
    }
 
    public async void actor_setup()
    {
        // Wait for the first physics frame so the NavigationServer can sync.
        // On the first frame the NavigationServer map has not synchronized region
        // data and any path query will return empty. Await one frame to pause
        // scripts until the NavigationServer had time to sync.
        
        //await ToSignal(GetTree(), "physics_frame");
        await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame);        
        // physics_frame
        // Emitted immediately before Node._physics_process is called on every node
        // in the SceneTree.
 
        // Now that the navigation map is no longer empty, set the movement target.
        set_movement_target(movement_target_position);
    }
 
    public void set_movement_target(Vector2 movement_target)
    {
        navigation_agent.TargetPosition = movement_target;
    }
 
    public override void _PhysicsProcess(double delta)
    {        
        if (navigation_agent.IsNavigationFinished())
        {
            return;
        }
 
        //Vector2 current_agent_position = GlobalPosition;
        //Vector2 next_path_position = navigation_agent.GetNextPathPosition();
        //Vector2 new_velocity = next_path_position - current_agent_position;
        Vector2 new_velocity = ToLocal(navigation_agent.GetNextPathPosition());
 
        new_velocity = new_velocity.Normalized();
        new_velocity = new_velocity * movement_speed;
 
        Velocity = new_velocity;
        MoveAndSlide();
    }
}
 

 

 

CharacterBody2D에 추가한 스크립트에 2D 네비게이션 사용 코드를 작성한다.

movement_target_position은 목표 지점을 적당히 지정한다.

 

목표지점까지 캐릭터가 진행하는 경로가 표시되며 이동한다.

 

이번엔 마우스 포인터를 따라가도록 해 보자.

 

Navigation Polygon을 수정한다.

 

 

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
31
32
33
34
35
36
using Godot;
 
public partial class Nav : CharacterBody2D
{
    public float movement_speed = 200.0f;
    public NavigationAgent2D navigation_agent;
 
    public override void _Ready()
    {
        navigation_agent = GetNode<NavigationAgent2D>("NavigationAgent2D");
 
        navigation_agent.PathDesiredDistance = 4.0f;
        navigation_agent.TargetDesiredDistance = 4.0f;
    }
 
    public override void _Process(double delta)
    {
        navigation_agent.TargetPosition = GetGlobalMousePosition();
    }
 
    public override void _PhysicsProcess(double delta)
    {
        if (navigation_agent.IsNavigationFinished())
        {
            return;
        }
 
        Vector2 new_velocity = ToLocal(navigation_agent.GetNextPathPosition());
        new_velocity = new_velocity.Normalized();
        new_velocity = new_velocity * movement_speed;
 
        Velocity = new_velocity;
 
        MoveAndSlide();
    }
}
 

 

 

마우스 포인터를 따라가는 코드를 작성한다.

 

Navigation Polygon 내에서 마우스를 따라 움직인다.

 

이번엔 타일맵을 이용해 맵을 만들고 길을 찾아보자.

Tile-Sets (64-64).png
0.01MB

 

NavigationRegion2D를 삭제하고 TileMap을 추가해 위와 같이 맵을 만든다.

TileMap에 Physics Layer와 Navigation Layer를 하나씩 추가한다. 각 타일의 설정은 아래 내용을 참고한다.

 

여러 타일 중 두 가지만(벽과 길) 사용해 맵을 만들어 보자. 벽으로 사용할 타일에 Physics(Collision) Polygon을 생성한다.

 

 

길로 사용할 타일에 Navigation Polygon을 생성한다.

 

CharacterBody2D의 설정도 바꿔야 한다.

● Motion Mode - Floating

● Wall Min Slide Angle - 0

● 자식노드의 CollisionShape2D - Shape이 사각형이라면 원으로 바꾼다.

이렇게 변경하지 않으면 캐릭터가 이동 중 모서리에 걸려 움직이지 못하는 경우가 발생한다.

스크립트는 변경할 필요 없다.

 

게임을 실행하면 마우스를 따라 캐릭터가 길을 찾고 이동한다.

 

※ 참고

2D Navigation Overview

Using NavigationAgents

 

반응형
Posted by J-sean
:

[Godot] Wall Jump 벽 점프

Godot 2023. 10. 2. 16:53 |
반응형

벽을 타고 점프해 보자.

 

바닥, 벽, 캐릭터를 적당히 배치한다. 캐릭터에는 스크립트를 추가하자.

 

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
31
32
33
34
35
36
using Godot;
 
public partial class CharacterBody2D : Godot.CharacterBody2D
{
    public const float Speed = 300.0f;
    public const float JumpVelocity = -400.0f;
 
    public float gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();
 
    public override void _PhysicsProcess(double delta)
    {
        Vector2 velocity = Velocity;
 
        if (!IsOnFloor())
            velocity.Y += gravity * (float)delta;
        
        if (Input.IsActionJustPressed("ui_accept"&& IsOnFloor())
            velocity.Y = JumpVelocity;
 
        if (Input.IsActionJustPressed("ui_accept"&& IsOnWallOnly())
            velocity.Y = JumpVelocity;
 
        Vector2 direction = Input.GetVector("ui_left""ui_right""ui_up""ui_down");
        if (direction != Vector2.Zero)
        {
            velocity.X = direction.X * Speed;
        }
        else
        {
            velocity.X = Mathf.MoveToward(Velocity.X, 0, Speed);
        }
 
        Velocity = velocity;
        MoveAndSlide();
    }
}
 

 

 

IsOnWallOnly() 함수를 사용한 스크립트를 작성한다. 

 

벽을 타고 wall jump가 가능하다.

 

※ 참고

CharacterBody2D

Using CharacterBody2D/3D

 

반응형
Posted by J-sean
:
반응형

타일맵에 Collision Layer, Collision Mask를 설정하고 게임 실행 중 코드에서 Custom Data에 따라 적절히 바꿀 수 있다.

 

타일맵을 준비한다.

 

TileMap - Tile Set- Physics Layers - Collision Layer/Mask를 설정한다.

 

TileMap - Tile Set - Custom Data Layers에 원하는 데이터 이름과 타입을 설정한다.

 

Custom Data를 지정할 타일을 선택하고 Custom Data에 원하는 데이터 값을 설정한다. 위에서 bool 타입을 설정했기 때문에 On(True)이 표시된다. (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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using Godot;
 
public partial class player : Node2D
{
    [Export]
    CharacterBody2D character;
 
    public override void _Ready()
    {
        //character = GetNode<CharacterBody2D>("CharacterBody2D");
    }
 
    public override void _Process(double delta)
    {
        Vector2I mousePosition = GetNode<TileMap>("TileMap").LocalToMap(GetViewport().GetMousePosition());
        // 마우스 커서 위치를 타일맵 좌표로 변환한다.
        int layers = GetNode<TileMap>("TileMap").GetLayersCount();
        // 타일맵 레이어 갯수를 가져온다.
 
        for (int layer = 0; layer < layers; layer++)
        {
            TileData td = GetNode<TileMap>("TileMap").GetCellTileData(layer, mousePosition);
            // 마우스가 위치한 타일의 타일 데이터를 가져온다.
            if (td != null)
            {
                GD.Print($"Layer: {layer}");
                GD.Print($"CustomData: {td.GetCustomData("extraData")}");
                // TileMap - Inspector - Custom Data Layers 에서 추가한 변수를
                // TileSet탭 - Tiles탭 - Select - Custom Data 에서 세팅한 값.
 
                //GetNode<TileMap>("TileMap").TileSet.SetPhysicsLayerCollisionLayer(layer, 8);
                //GetNode<TileMap>("TileMap").TileSet.SetPhysicsLayerCollisionMask(layer, 16);
                // extraData 값을 확인하고 그에 맞게 레이어 값을 바꿀 수 있다.
 
                //int groundLayer = 1;
                //int buildingLayer = 2;
                //character.SetCollisionLayerValue(groundLayer, false);
                //character.SetCollisionMaskValue(buildingLayer, true);
                // 아니면 상화에 따라 캐릭터의 collision layer/mask 값을 바꿀 수 있다.
                // 주의할 점은 SetCollisionXXXValue()의 레이어 값은 1~32이므로 미리 변경하고 싶은
                // 레이어 번호를 변수에 저장하고 사용하자. 0 이 들어가면 안된다.
            }
            else
            {
                GD.Print("NULL");
            }
 
            GD.Print($"Collision Layer:" +
                $"{GetNode<TileMap>("TileMap").TileSet.GetPhysicsLayerCollisionLayer(layer)}");
            GD.Print($"Collision Mask:" +
                $"{GetNode<TileMap>("TileMap").TileSet.GetPhysicsLayerCollisionMask(layer)}");
            // 1번 레이어(마스크) value: 1
            // 2번 레이어(마스크) value: 2
            // 3번 레이어(마스크) value: 4
            // 4번 레이어(마스크) value: 8
            // ... 9번 레이어(마스크) value: 256 ...
        }
    }
}
 

 

 

스크립트를 작성한다.

 

게임을 실행하면 마우스 위치에 따라 정보가 표시된다.

 

반응형

'Godot' 카테고리의 다른 글

[Godot] 2D Navigation Basic Setup  (0) 2023.10.06
[Godot] Wall Jump 벽 점프  (0) 2023.10.02
[Godot] RayCast2D C# Example  (0) 2023.09.27
[Godot] Area2D Gravity 중력  (0) 2023.09.27
[Godot] AddChild(), RemoveChild()  (0) 2023.09.26
Posted by J-sean
:

[Godot] RayCast2D C# Example

Godot 2023. 9. 27. 17:45 |
반응형

RayCast2D C# 예제.

 

씬을 준비하고 RayCast2D와 스크립트를 추가한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    public override void _Draw()
    {
        DrawLine(GetNode<RayCast2D>("RayCast2D").Position,
            GetNode<RayCast2D>("RayCast2D").Position +
            GetNode<RayCast2D>("RayCast2D").TargetPosition,
            new Color(1000.5f), 5);
        // Ray를 확인할 수 있도록 선으로 표시한다.
    }
 
    public override void _PhysicsProcess(double delta)
    {    
        if (GetNode<RayCast2D>("RayCast2D").IsColliding())
        {
            Node obj = GetNode<RayCast2D>("RayCast2D").GetCollider() as Node;            
            GD.Print(obj.Name);
            // Ray와 충돌한 오브젝트의 이름을 출력한다.
        }
   ...
 

 

 

스크립트를 작성하고 실행하면 Ray와 충돌하는 오브젝트의 이름이 출력된다.

 

※ 참고

RayCast2D

 

반응형
Posted by J-sean
: