使用Unreal Engine Python插件 + 和风天气API

在引擎内获取实时天气信息

先上效果

编译前配置:创建一个空Actor蓝图,加入Python Component,设置”Python”内容如下:

Screenshot-1.png

创建一个名为”CityName”的变量,用于传入城市信息,默认值设置为”北京”:

Screenshot-2.png

将Actor拖放到场景中

Screenshot-3.png

由于Unreal Engine Python对代码缩进有较为严格的要求,故这里使用了插件自带的Pip8-ize脚本对代码内容进行了优化,看起来可能有点怪

import unreal_engine as ue
import urllib.request
import gzip


class WeatherComponent:

    def begin_play(self):

        city_name = self.uobject.get_owner().CityName
        urllib.parse.quote(city_name)
        url = "https://free-api.heweather.net/s6/weather/now?location=" + \
            urllib.parse.quote(city_name) + \
            "&key=[这里是你的key]"
        weather_data = urllib.request.urlopen(url).read()
        weather_data = weather_data.decode('utf-8')
        weather_dict = eval(weather_data)
        ue.print_string('-----Basic Information-----')
        ue.print_string(
            'City: ' + weather_dict['HeWeather6'][0]['basic']['location'])
        ue.print_string(
            'City / District Code: ' + weather_dict['HeWeather6'][0]['basic']['cid'])
        ue.print_string(
            'City / region Latitude: ' + weather_dict['HeWeather6'][0]['basic']['lat'])
        ue.print_string(
            'City / region Longitude: ' + weather_dict['HeWeather6'][0]['basic']['lon'])
        ue.print_string(
            'City / Parent city of the region :' + weather_dict['HeWeather6'][0]['basic']['parent_city'])
        ue.print_string(
            'City / Administrative area of the region: ' + weather_dict['HeWeather6'][0]['basic']['admin_area'])
        ue.print_string(
            'City / Country name of the region: ' + weather_dict['HeWeather6'][0]['basic']['cnty'])
        ue.print_string(
            'City / City time zone: ' + weather_dict['HeWeather6'][0]['basic']['tz'])
        ue.print_string('-----Updated Time-----')
        ue.print_string(
            'Local Time: ' + weather_dict['HeWeather6'][0]['update']['loc'])
        ue.print_string(
            'UTC Time: ' + weather_dict['HeWeather6'][0]['update']['utc'])
        ue.print_string('-----Live Weather-----')
        ue.print_string(
            'Somatosensory temperature / oC: ' + weather_dict['HeWeather6'][0]['now']['fl'])
        ue.print_string(
            'Temperature / oC: ' + weather_dict['HeWeather6'][0]['now']['tmp'])
        ue.print_string(
            'Description of actual weather conditions: ' + weather_dict['HeWeather6'][0]['now']['cond_txt'])
        ue.print_string(
            'Direction of wind: ' + weather_dict['HeWeather6'][0]['now']['wind_dir'])
        ue.print_string(
            'Wind force: ' + weather_dict['HeWeather6'][0]['now']['wind_sc'])
        ue.print_string(
            'Precipitation: ' + weather_dict['HeWeather6'][0]['now']['pcpn'])
        ue.print_string(
            'Cloudiness: ' + weather_dict['HeWeather6'][0]['now']['cloud'])

发表评论

邮箱地址不会被公开。