반응형

타일맵에 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
:
반응형

WebRequest 클래스를 이용해 웹페이지 데이터(내용)를 요청해 보자.

 

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Net;
using System.IO;
 
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            WebRequest webRequest = null;
            WebResponse webResponse = null;
 
            Stream stream = null;
            StreamReader streamReader = null;
 
            try
            {
                Console.Write("Enter URI: ");
                string uriString = Console.ReadLine();
 
                webRequest = WebRequest.Create(uriString.Trim());
                // If required by the server, set the credentials.
                webRequest.Credentials = CredentialCache.DefaultCredentials;
 
                webResponse = webRequest.GetResponse();
                Console.WriteLine("WebResponse status: " + ((HttpWebResponse)webResponse).StatusDescription);
 
                stream = webResponse.GetResponseStream();
                streamReader = new StreamReader(stream);
 
                string readString = streamReader.ReadToEnd();
                Console.WriteLine(readString);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
            finally
            {
                if (webResponse != null)
                    webResponse.Close();
                if (streamReader != null)
                    streamReader.Close();
                if (stream != null)
                    stream.Close();
            }
        }
    }
}
 

 

소스를 작성하고 빌드한다.

 

원하는 URI를 입력하면 데이터가 출력된다.

 

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

You can retrieve the contact data.

연락처 정보를 모두 받아 올 수 있다.


<AndroidManifest.xml>

1
2
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.WRITE_CONTACTS"/>


<MainActivity.java>

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
public class MainActivity extends AppCompatActivity {
 
    private final int MY_PERMISSION_REQUEST_CONTACTS = 1001;
    private final int MY_ACTIVITY_REQUEST_CODE = 2001;
 
    TextView textView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        String[] permissionRequests = {
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_CONTACTS
        };
 
        checkPermissions(permissionRequests);
 
        textView = findViewById(R.id.textView);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseContacts();
            }
        });
    }
 
    public void checkPermissions(String[] permissionRequests) {
        final ArrayList<String> permissionRequestList = new ArrayList<String>();
 
        for (final String request : permissionRequests) {
            if (ContextCompat.checkSelfPermission(this, request) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, request)) {   // Redundant in this case
                    permissionRequestList.add(request);
                } else {
                    permissionRequestList.add(request);
                }
            }
        }
 
        if (!permissionRequestList.isEmpty()) {
            final String[] results = new String[permissionRequestList.size()];
            permissionRequestList.toArray(results);
 
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("info");
 
            String msg = "This app won't work properly unless you grant below permissions.";
            for (String str : results)
                msg += ("\n- "+ str);
 
            builder.setMessage(msg);
            builder.setIcon(android.R.drawable.ic_dialog_info);
 
            builder.setNeutralButton("OK"new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(MainActivity.this, results, MY_PERMISSION_REQUEST_CONTACTS);
                }
            });
 
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSION_REQUEST_CONTACTS: {
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(this, permissions[i] + " permission granted.", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, permissions[i] + " permission denied.", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }
 
    public void chooseContacts() {
        Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(contactPickerIntent, MY_ACTIVITY_REQUEST_CODE);
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == MY_ACTIVITY_REQUEST_CODE) {
                try {
                    Uri contactsUri = data.getData();
                    String id = contactsUri.getLastPathSegment();
 
                    getContacts(id);
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
 
    public void getContacts(String id) {
        Cursor cursor;
        String name;
        String phone;
 
        try {
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
                    new String[] {id},
                    null);
 
            if (cursor.moveToFirst()) {
                name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                textView.setText("Name: " + name + '\n' + "Phone: " + phone + '\n');
 
                String columns[] = cursor.getColumnNames();
                for (String column : columns) {
                    int index = cursor.getColumnIndex(column);
                    String columnOutput = ("#" + index + " -> [" + column + "] = " + cursor.getString(index));
                    textView.append('\n' + columnOutput);
                }
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}




Run the app.


Choose contact.


Display contact data.


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

You can retrieve multiple sensor data at the same time. Say you need ACCELEROMETER and AMBIENT_TEMPERATURE data.

동시에 여러가지 센서 데이터를 받아 올 수 있다. 예를 들어 ACCELEROMETER 와 AMBIENT_TEMPERATURE 센서의 데이터를 받아 오자.


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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
public class MainActivity extends AppCompatActivity {
 
    TextView textView;
    TextView textView2;
 
    SensorManager manager;
    List<Sensor> sensors;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView = findViewById(R.id.textView);
        textView2 = findViewById(R.id.textView2);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manager = (SensorManager)getSystemService(SENSOR_SERVICE);
                sensors = manager.getSensorList(Sensor.TYPE_ALL);
 
                int index = 0;
                for (Sensor sensor : sensors) {
                    textView.append("#" + index++ + ": " + sensor.getName() + '\n');
                }
            }
        });
 
        final SensorEventListener sensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                    String str = "Sensor Timestamp: " + event.timestamp + "\n\n";
                    str = str + "Sensor Accuracy: " + event.accuracy + '\n';
 
                    for (int index = 0; index < event.values.length; index++) {
                        str += ("Sensor Value #" + index + ": " + event.values[index] + '\n');
                    }
 
                    textView.setText(str);
                }
 
                if (event.sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE) {
                    String str = "Sensor Timestamp: " + event.timestamp + "\n\n";
                    str = str + "Sensor Accuracy: " + event.accuracy + '\n';
 
                    for (int index = 0; index < event.values.length; index++) {
                        str += ("Sensor Value #" + index + ": " + event.values[index] + '\n');
                    }
 
                    textView2.setText(str);
                }
            }
 
            /*
            SENSOR_STATUS_ACCURACY_HIGH
            This sensor is reporting data with maximum accuracy
            Constant Value: 3 (0x00000003)
            SENSOR_STATUS_ACCURACY_LOW
            This sensor is reporting data with low accuracy, calibration with the environment is needed
            Constant Value: 1 (0x00000001)
            SENSOR_STATUS_ACCURACY_MEDIUM
            This sensor is reporting data with an average level of accuracy, calibration with the environment may improve the readings
            Constant Value: 2 (0x00000002)
            SENSOR_STATUS_NO_CONTACT
            The values returned by this sensor cannot be trusted because the sensor had no contact with what it was measuring
            (for example, the heart rate monitor is not in contact with the user).
            Constant Value: -1 (0xffffffff)
            SENSOR_STATUS_UNRELIABLE
            The values returned by this sensor cannot be trusted, calibration is needed or the environment doesn't allow readings
            Constant Value: 0 (0x00000000)
            */
 
            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
 
            }
        };
 
        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manager.registerListener(sensorEventListener, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
                // If sensors.get(0) == manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)...
                //manager.registerListener(sensorEventListener, sensors.get(0), SensorManager.SENSOR_DELAY_UI);
                manager.registerListener(sensorEventListener, manager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE), SensorManager.SENSOR_DELAY_UI);
            }
        });
 
        Button button3 = findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manager.unregisterListener(sensorEventListener, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
                // If sensors.get(0) == manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)...
                //manager.unregisterListener(sensorEventListener, sensors.get(0));
                manager.unregisterListener(sensorEventListener, manager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE));
            }
        });
    }
}



Sensor List


Sensor data


반응형
Posted by J-sean
: