コード 貼っておきます。
投稿者: Keita N
python バフェット流 バリュー投資判断
数年前、とある会合に呼ばれ、親切な方からバフェット流バリュー投資判断の技を教えてもらいました。
そのときのエッセンスをすべて詰め込んだスクリプトがこれです。
しかし、久々に実行してみると動きません。
とはいえ、大事な判断基準はこのスクリプトの中に入っているはずなので、読解してみると有益かもしれません。
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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
import logging import pandas as pd from selenium import webdriver from time import sleep def find_stock(stock_number=4816): driver=webdriver.Chrome(r"C:\driver\chromedriver_win32\chromedriver.exe") #ウェブドライバを読み込む # 株式番号を入力して、キー レーションの一覧を表示する url=r"https://www.morningstar.com/stocks/XTKS/"+str(stock_number)+r"/quote.html" driver.get(url) sleep(3) print("ブラウザを開きました") # 現在の株価を取得する xpath_price=r'//*[@id="message-box-price"]' price=driver.find_element_by_xpath(xpath_price).text # \ と カンマを削除してfloat化する print(price) price=price.replace(chr(165),"") .replace(".00","").replace(",","") price=float(price) print(price) #キーレーションタブを押す xpath_key_rations=r'//*[@id="sal-components-quote"]/div[2]/div/div/div/div[2]/div[1]/div/ul/li[3]/a' tub_key_rations=driver.find_element_by_xpath(xpath_key_rations) tub_key_rations.click() sleep(2) print("キーレーション タブを押しました") #フルキータブを押す xpath_full_key=r'//*[@id="sal-components-quote"]/div[2]/div/div/div/div[2]/div[2]/div/div[2]/div/a' tub_full_key_rations=driver.find_element_by_xpath(xpath_full_key) tub_full_key_rations.click() sleep(1) print("フルキータブを押しました") # アクティブなURLを切り替える print(driver.current_url) # 現在アクティブなURLを確認する driver.switch_to.window(driver.window_handles[1]) # アクティブなURLを切り替える sleep(2) print(driver.current_url) # URLが切り替わっていることを確認する # -------------------------------------------------------------------------------------------- # Earnings Per Share を取得 xpath_eps=r'//*[@id="i5"]' key_eps=driver.find_element_by_xpath(xpath_eps).text eps=[] for i in range(1,12): xpath_eps=r'//*[@id="financials"]/table/tbody/tr[12]/td['+str(i)+']' #eps.append(float(driver.find_element_by_xpath(xpath_eps).text)) print(float(driver.find_element_by_xpath(xpath_eps).text)) print(type([float(driver.find_element_by_xpath(xpath_eps).text)])) eps.append([float(driver.find_element_by_xpath(xpath_eps).text)]) eps={key_eps:eps} sleep(1) sleep(1) print(eps) # Dividends を取得 xpath_dividends=r'//*[@id="i6"]' key_dividends=driver.find_element_by_xpath(xpath_dividends).text dividends=[] dividends+=[None] for i in range(2,12): xpath_dividends=r'//*[@id="financials"]/table/tbody/tr[14]/td['+str(i)+']' dividends+=[float(driver.find_element_by_xpath(xpath_dividends).text)] dividends={key_dividends:dividends} sleep(1) print(dividends) # Book Value Per Share を取得 xpath_book=r'//*[@id="i8"]' key_book=driver.find_element_by_xpath(xpath_book).text book=[] for i in range(1,12): xpath_book=r'//*[@id="financials"]/table/tbody/tr[20]/td['+str(i)+']' book+=[float(driver.find_element_by_xpath(xpath_book).text)] book={key_book:book} sleep(1) print(book) # Return on Equity % を取得 # Key Rationsタブを Profitability に切り替える xpath_growth=r'//*[@id="keyStatWrap"]/div/ul/li[1]/a' tub_growth=driver.find_element_by_xpath(xpath_growth) tub_growth.click() #sleep(0.1) print("Profitabilityタブへ切り替え完了") xpath_roe=r'//*[@id="i26"]' key_roe=driver.find_element_by_xpath(xpath_roe).text roe=[] for i in range(1,12): xpath_roe=r'//*[@id="tab-profitability"]/table[2]/tbody/tr[12]/td['+str(i)+']' roe+=[driver.find_element_by_xpath(xpath_roe).text] roe={key_roe:roe} sleep(1) print(roe) # Key Rationsタブを Growth に切り替える xpath_growth=r'//*[@id="keyStatWrap"]/div/ul/li[2]/a' tub_growth=driver.find_element_by_xpath(xpath_growth) tub_growth.click() sleep(1) print("Growthタブへ切り替え完了") # EPS % を取得 xpath_eps_pct=r'//*[@id="gr-eps"]' key_eps_pct=driver.find_element_by_xpath(xpath_eps_pct).text eps_pct=[] xpath_eps_pct_yoy=r'//*[@id="tab-growth"]/table/tbody/tr[34]/td[10]' xpath_eps_pct_3y=r'//*[@id="tab-growth"]/table/tbody/tr[36]/td[10]' xpath_eps_pct_5y=r'//*[@id="tab-growth"]/table/tbody/tr[38]/td[10]' xpath_eps_pct_10y=r'//*[@id="tab-growth"]/table/tbody/tr[40]/td[10]' eps_pct.append(float(driver.find_element_by_xpath(xpath_eps_pct_yoy).text)) eps_pct.append(float(driver.find_element_by_xpath(xpath_eps_pct_3y).text)) eps_pct.append(float(driver.find_element_by_xpath(xpath_eps_pct_5y).text)) eps_pct.append(float(driver.find_element_by_xpath(xpath_eps_pct_10y).text)) eps_pct={key_eps_pct:eps_pct} sleep(1) print(eps_pct) # データフレームを作成 : pd.concatでどんどんつなげていく。 # 軸を指定して、自動ソートを無効にする。: axis=1 df=pd.concat([pd.DataFrame(eps), pd.DataFrame(dividends), pd.DataFrame(book), pd.DataFrame(roe), pd.DataFrame(eps_pct)], axis=1) print(df) stock_price=3425 as_asset=False as_dividends=False as_growths=False df.keys() """ Index(['Earnings Per Share JPY', 'Dividends JPY', 'Book Value Per Share * JPY', 'Return on Equity %', 'EPS %'], dtype='object') """ print("現在の株価 : ",price) #(1)assets:ずっと持ち続ける資産株として # 直近のTTMに注目する book_value_per_share_ttm=book_value_per_share_ttm=df['Book Value Per Share * JPY'][len(df['Book Value Per Share * JPY'])-1] entry_1=book_value_per_share_ttm*0.8 review_1=book_value_per_share_ttm*1.0 if price<=entry_1: as_asset=True print("資産株として 買い判定:{} エントリー価格 :{:.0f} レビュー価格:{:.0f}".format(as_asset,entry_1,review_1)) #(2)devidents:配当用の株として # 欲しい利回り日本株6%(米国株7%) 欲しい配当率 Yw 0.0 # Devidents / yield_target dividends_ttm=df['Dividends JPY'][len(df['Dividends JPY'])-1] yield_target=0.06 # 固定値 entry_2=dividends_ttm/yield_target review_2=entry_2*1.5 # 単純に1.5倍 if price<=entry_2: as_dividends=True print("配当株として 買い判定:{} エントリー価格 :{:.0f} レビュー価格:{:.0f}".format(as_dividends,entry_2,review_2)) #(3)growths:成長株として eps_ttm=df['Earnings Per Share JPY'][len(df['Earnings Per Share JPY'])-1] eps_pct=df['EPS %'].min() entry_3=eps_ttm*eps_pct review_3=entry_3*1.2 # 単純に1.2倍 if price<=entry_3: as_growths=True print("成長株として 買い判定:{} エントリー価格 :{:.0f} レビュー価格:{:.0f}".format(as_growths,entry_3,review_3)) print("証券NO. : ",stock_number) print("現在の株価 : ",int(price)) print("資産株として 買い判定:{} エントリー価格 :{:.0f} レビュー価格:{:.0f}".format(as_asset,entry_1,review_1)) print("配当株として 買い判定:{} エントリー価格 :{:.0f} レビュー価格:{:.0f}".format(as_dividends,entry_2,review_2)) print("成長株として 買い判定:{} エントリー価格 :{:.0f} レビュー価格:{:.0f}".format(as_growths,entry_3,review_3)) return "完了" |
Python:webカメラとOpenCVで動体検知してLine Notifyで画像を通知する
こんにちは Keita Nakamorです。久々の投稿です。
今日は、webカメラとOpenCVで動体検知してLine Notifyで画像を通知する 、ってことをやってみます。
予めアクセストークンをLine Notifyでとっておいて下さい。Bearer <ここにアクセストークンをはる> ってところに貼り付けます。<>は入りませんよ。
久々すぎるのでOpenCVの基礎からやっていきます。
ステップ1:静止画像ファイルを読み込んで出力する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# ステップ1:静止画像ファイルを読み込んで出力する import os import cv2 import numpy as np img =cv2.imread('Pictures/Screenpresso/2020-03-27_17h43_20.png') # 画像サイズを調べる img.shape # (1040, 1920, 3) # BGR の数値を確認する img[0][0] # array([65, 63, 60], dtype=uint8) # 画像を出力する cv2.imshow('img', img) cv2.waitKey(0) cv2.destroyAllWindows() # 画像をファイルに出力する #os.mkdir('./output') cv2.imwrite('output/test.jpg', img) |
ステップ2動画ファイルを読み込んで出力する→リアルタイムキャプチャーする
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 |
# ステップ2動画ファイルを読み込んで出力する→リアルタイムキャプチャーする import cv2 import numpy as np import sys '''# 動画を読み込む cap = cv2.VideoCapture('output/test.avi') ''' # リアルタイムキャプチャーする cap = cv2.VideoCapture(0) # 動画読み込みが失敗したら強制終了 if cap.isOpened() == False: print('読み込み失敗') sys.exit() #1フレームだけ読み込む ret, frame = cap.read() h, w, color = frame.shape # h,wの順 3つ目は色数 # 書き込み設定(コーデックの指定) fourcc = cv2.VideoWriter_fourcc(*'XVID') dst = cv2.VideoWriter('output/test001.avi', fourcc, 30.0, (w,h)) # ファイル名 設定 fps 解像度の順 # スクリプト実行 while True: ret, frame = cap.read() if ret == False: break # 表示 cv2.imshow('img', frame) # 書き込み dst.write(frame) # 停止動作 if cv2.waitKey(30) == 27: # ESC=27 break # 終了処理 cv2.destroyAllWindows() cap.release() |
ステップ3 リアルタイムキャプチャー と リアルタイム背景差分処理
アクセストークンは、Line Notifyから取得して<>内にコピペしてください。かっこ部分は削除してください。
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 |
# ステップ3 リアルタイムキャプチャー と リアルタイム背景差分処理 import cv2 import numpy as np import sys import time import datetime import requests def line_informer(file_name): # 条件 : request_headers = {'Authorization': 'Bearer <ここにアクセストークンをはる>'} payload = {'message': 'Detected {}.'.format(datetime.datetime.now())} #files = {'imageFile': open("dorobou_picking.png", "rb")} #バイナリファイルを開く files = {'imageFile': open('output/' + file_name , "rb")} # 通知系 API のエンドポイントのホスト名は notify-api.line.me #r = requests.post('https://notify-api.line.me/api/notify', headers=request_headers, data=payload) r = requests.post('https://notify-api.line.me/api/notify', headers=request_headers, data=payload, files=files) print(r.json()) def line_informer_start(): #スクリプトが実行されたことを通知する payload = {'message': 'Monitoring Start' } request_headers = {'Authorization': 'Bearer <ここにアクセストークンをはる>'} # 通知系 API のエンドポイントのホスト名は notify-api.line.me r = requests.post('https://notify-api.line.me/api/notify', headers=request_headers, data=payload) print(r.json()) line_informer_start() '''# テスト用:動画を読み込む cap = cv2.VideoCapture('output/test.avi') ''' # リアルタイムキャプチャーする cap = cv2.VideoCapture(0) # 動画読み込みが失敗したら強制終了 if cap.isOpened() == False: print('読み込み失敗') sys.exit() #1フレームだけ読み込んで h ,w を取り出す ret, frame = cap.read() h, w, ch = frame.shape # h,wの順 3つ目は色数 # 書き込み設定(コーデックの指定) time_str = str(datetime.datetime.now()) file_name = time_str[:10]+ '_' +time_str[11:13]+ time_str[14:16] + time_str[17:19] + '.avi' print(time_str) fourcc = cv2.VideoWriter_fourcc(*'XVID') fps =30 dst = cv2.VideoWriter('output/' + file_name, fourcc, fps, (w,h)) # ファイル名 設定 fps 解像度の順 # 背景差分の行列領域を確保 frame_back = np.zeros((h,w,ch),dtype=np.float32) # アラート時間インターバルの初期化 previous_datetime = datetime.datetime.now() # スクリプト実行 while True: ret, frame = cap.read() if ret == False: break # 画像処理 #frame2 = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # グレースケール frame3= cv2.absdiff(frame.astype(np.float32), frame_back) # 背景差分 cv2.accumulateWeighted(frame,frame_back, 0.2) # 差分の大きさ pix_value= int(frame3.sum()/10000) cv2.putText(frame, 'Pix_value:{}'.format(pix_value), (0, 50), cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 5, cv2.LINE_AA) cv2.putText(frame3, 'Pix_value:{}'.format(pix_value), (0, 50), cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 5, cv2.LINE_AA) # しきい値としきい値を超えたときに録画REC表示する sreshold = 500 if pix_value > sreshold: # ラインに通知する(ただし 前回通知から30sec以上間隔をあけること) time_delta = datetime.datetime.now() - previous_datetime if time_delta.seconds > 10: # 画像をファイルに出力する #os.mkdir('./output') time_str = str(datetime.datetime.now()) file_name = time_str[:10]+ '_' +time_str[11:13]+ time_str[14:16] + time_str[17:19] + '.jpg' cv2.imwrite('output/' + file_name, frame) line_informer(file_name) previous_datetime = datetime.datetime.now() # REC表示 cv2.putText(frame, 'Jadge:{}'.format('REC'), (0, 100), cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 5, cv2.LINE_AA) cv2.putText(frame3, 'Jadge:{}'.format('REC'), (0, 100), cv2.FONT_HERSHEY_PLAIN, 4, (255, 255, 255), 5, cv2.LINE_AA) # REC保存 dst.write(frame) # リアルタイム表示 cv2.imshow('img', frame) #cv2.imshow('img2', frame2) #グレースケール cv2.imshow('img3', frame3.astype(np.uint8)) # 背景差分 # 停止動作 if cv2.waitKey(30) == 27: # ESC=27 break # 終了処理 cv2.destroyAllWindows() cap.release() |
以上
グラフ 第2軸の作り方
matplotlibを使って2軸あるグラフを作成してみます。
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 |
import numpy as np import matplotlib.pyplot as ple %matplotlib inline # サンプルデータ生成 np.random.seed(0) time = np.arange(0,11) values = np.random.randn(11).cumsum() values2 = np.random.randn(11).cumsum() * 2 #枠を確保 fig = plt.figure(figsize=(10, 5)) # サブプロットを使用する ax1 = fig.add_subplot(1,1,1) ax1.scatter(time, values, label='test data') ax1.plot(time, values, label='simulation') ax1.set_xlabel('Time t / s') ax1.set_ylabel('Value') ax1.legend(loc='best') # ここまでは同じ # 第2軸を設定する ax2 = ax1.twinx() #Timeを共通として第2軸を定義する ツインメソド ax2.scatter(time, values2, label='test data 2', color='blue', marker='x', ) ax2.plot(time, values2, label='simulation 2', color='blue') # この時点ではグリッドが2軸分重なってしまっているので修正が必要 ax1.set_ylim([0, 10]) ax2.set_ylim([0, 10]) ax2.grid(False) # 凡例がまだかぶっている ax1.legend(bbox_to_anchor=(1.38, 0.8)) ax2.legend(bbox_to_anchor=(1.40, 0.5)) # グラフを保存する plt.tight_layout() plt.savefig('data/fig_001.png', dpi=300) |
Python3: 3Dプロット from mpl_toolkits.mplot3d import Axes3D
3Dプロットのやりかたです。
モジュールは
from mpl_toolkits.mplot3d import Axes3D
%matplotlib notebook
を使っていきます。
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 |
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib notebook # サンプルデータ:粒子のブラウン運動を模擬 x = np.random.randn(100).cumsum() #1ステップ毎に移動していく状態を累積cumsumで表現 y = np.random.randn(100).cumsum() z = np.random.randn(100).cumsum() value = np.random.randn(100).cumsum() # ggplotのスタイルを使用する plt.style.use('ggplot') # 枠を確保 fig = plt.figure() # figを 3Dへ 変換 ax = Axes3D(fig) ax.plot(x, y, z, label='particle moving', color ='black') # カラーバー mappable = ax.scatter(x, y, z, c=value, cmap='bwr') fig.colorbar(mappable, ax=ax) # タイトル ラベルを設定 ax.set_title('title') ax.set_xlabel('xlabel') ax.set_ylabel('ylabel') ax.set_zlabel('zlabel') # 凡例を設定 ax.legend() # リミットを設定 ax.set_xlim(-10, +10) ax.set_ylim(-10, +10) ax.set_zlim(-10, +10) # グリッドを表示 ax.grid(True) plt.show() |
ディレクトリの作成 削除
1 2 3 4 5 6 7 |
import os #ディレクトリ作成 os.mkdir('test') #ディレクトリ削除 os.rmdir('test') |
カレントディレクトリのテキストファイルのリストを作成する方法、リスト内包表記
1 2 3 4 5 6 7 8 9 10 11 12 |
# カレントディレクトリのテキストファイルのリストを作成する方法 import os cwd_path =os.getcwd() text_list = [] for i, j in enumerate(os.listdir(cwd_path)): if j[-4:] == '.txt': text_list.append([i,j]) text_list |
リスト内包表記を使うと3行が1行に短縮できる
1 2 3 4 5 6 7 8 |
#リスト内包表記 nums = [] for i in range(11): nums.append(i**2) nums nums2 = [i**2 for i in range(11)] nums2 |
リスト内包表記を使って、テキ
1 2 3 4 5 |
import os files = os.listdir() txt_files = [i for i in files if i[-4:] == '.txt'] txt_files |
ストファイルのみを抽出してみる
Unity:衝突
久々にUnityを触ってみました。
ボールをキューブにぶつけたときに、キューブが消滅してポイントが入ると動きです。
下準備
- 地面をプレーンで作成
- スフィア(Player)とキューブ(collier object)を出す
- プレーンの周りをキューブで囲んで壁にします。
Playerをキーボードで動かせるようにする。PlayerController.cs
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 |
public class PlayerController : MonoBehaviour { // Define Rigidbody-Type variable rb Rigidbody rb; // Define speed as pablic as inspector public float speed = 1; // Start is called before the first frame updates void Start() { Debug.Log("Script starts"); // Get rigidbody component from this object. // あとで力を与える対象として使用する rb = GetComponent<Rigidbody>(); } // Update is called once per frame void FixedUpdate() { //Debug.Log("FixedUpdating"); // 矢印キーを押すと 変数moveHに格納する。変数宣言も一緒にやっている。 float moveH = Input.GetAxis("Horizontal"); float moveV = Input.GetAxis("Vertical"); // 新しいVector3型の値を作って、変数moveに代入する Vector3 move = new Vector3(moveH, 0, moveV); // Vector3型変数moveをオブジェクトに対する力として与える rb.AddForce(move * speed); } |
さらに、オブジェクトに接触したときに、接触したものを検知して、見えなくし、点数が加算されるコードをいれます。
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 |
public class PlayerController : MonoBehaviour { // Define Rigidbody-Type variable rb Rigidbody rb; int count; // Define speed as pablic as inspector public float speed = 1; // Start is called before the first frame updates void Start() { Debug.Log("Script starts"); // Get rigidbody component from this object. // あとで力を与える対象として使用する rb = GetComponent<Rigidbody>(); } // Update is called once per frame void FixedUpdate() { //Debug.Log("FixedUpdating"); // 矢印キーを押すと 変数moveHに格納する。変数宣言も一緒にやっている。 float moveH = Input.GetAxis("Horizontal"); float moveV = Input.GetAxis("Vertical"); // 新しいVector3型の値を作って、変数moveに代入する Vector3 move = new Vector3(moveH, 0, moveV); // Vector3型変数moveをオブジェクトに対する力として与える rb.AddForce(move * speed); } // オントリガーメソドを定義する void OnTriggerEnter(Collider other) { // otherはコライダー、セットアクティブでチェックを外す other.gameObject.SetActive(false); count += 1; Debug.Log(count); } } |
衝突オブジェクトのis Trigerはチェックを入れておいて、上記のOnTriggerが機能するようにします。
衝突オブジェクトはくるくる回るようにしておきます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Rotator : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { this.transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime); } } |
カメラが、Playerをついてまわるようにします。
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 |
public class PlayerFollower : MonoBehaviour { // ゲームオブジェクトを入れるパブリック変数を定義しておく // 後でインスペクターからplayerオブジェクトを入れる public GameObject player; Vector3 offset; // Start is called before the first frame update void Start() { // 初期位置の差をoffsetとして得る offset = this.transform.position - player.transform.position; } // Update is called once per frame void LateUpdate() { // このスクリプトが適用されたオブジェクト(カメラ)の位置を // インスペクタで定義するゲームオブジェクトplayerに依存させる // this.transform.position = player.transform.position; // offsetを追加する this.transform.position = player.transform.position + offset; } } |
UIを追加します。UI Canvas Text をヒエラルキーへ追加します。
shift + alt +左クリックで 左上にTextをピン留めできます。
PlayerController.csへ得点を追加します。
モジュールUnityEngine.UIを追加
pubulic Text countTextを定義して、予め作っておいたcount変数を代入します。
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 |
using UnityEngine.UI; public class PlayerController : MonoBehaviour { // Define Rigidbody-Type variable rb Rigidbody rb; int count; public Text countText; // Define speed as pablic as inspector public float speed = 1; // Start is called before the first frame updates void Start() { Debug.Log("Script starts"); // Get rigidbody component from this object. // あとで力を与える対象として使用する rb = GetComponent<Rigidbody>(); count = 0; // UI canvasに入れられるのは文字だけ countText.text = "得点 : "+ count.ToString(); } // Update is called once per frame void FixedUpdate() { //Debug.Log("FixedUpdating"); // 矢印キーを押すと 変数moveHに格納する。変数宣言も一緒にやっている。 float moveH = Input.GetAxis("Horizontal"); float moveV = Input.GetAxis("Vertical"); // 新しいVector3型の値を作って、変数moveに代入する Vector3 move = new Vector3(moveH, 0, moveV); // Vector3型変数moveをオブジェクトに対する力として与える rb.AddForce(move * speed); } // オントリガーメソドを定義する void OnTriggerEnter(Collider other) { // otherはコライダー、セットアクティブでチェックを外す other.gameObject.SetActive(false); count += 1; Debug.Log(count); countText.text = "得点 : " + count.ToString(); } } |
public Textにはインスペクターから Canvas直下のTextオブジェクトをドラックアンドドロップで入れます。
2回繰り返すスクリプトは関数化します。
1 2 3 4 |
void SetCountText() { countText.text = "得点 : " + count.ToString(); } |
で、使うときはこうします。
1 |
SetCountText(); // 新メソド作成した |
保護中: pyautogui 例
MUP:動画編集
動画編集 adobe premire pro
・モーショングラフィックステンプレートを購入しよう
Morgt envatomarket(エンバトマーケット)で morgtと検索する
またはFlashback
・カット編集効率化 30%時間削減
まとめて選択>メニューのシーケンス>ギャップを詰める
メニュー>Premiere Pro>キーボードショートカット>カスタム>
Q:前の編集ポイントをリップルトリミング
W:編集点を追加
E:次の編集ポイントをリップルトリミング
1)Wで切断して、右に進んだところでEを押すと消える
2)Wで切断して、左に進んだところでQを押すと消える
・BGMを入れよう
著作権フリーの音源を使うこと
BGMサイト
NCS:名前を動画に入れること
課金 artlist, musicbed
効果音サイト
効果音ラボ クレジット表記を入れること
BGMの時間調整
adobe auition: マルチトラックセッション ミュージックとリミックスにチェック 秒数を入力>これだけ
・装飾
文字:icoon アイコンっぽい
freepik おすすめ、1日10個まで ハイクオリティbチラシ パンフレット photoshopテンプレ
パブリクドメインQ 著作権が切れた素材
フラットアイコンデザイン 資料でよく使う
イラストAC 背景画像
・クロマキー
ePhotolnc T57BG
背景の影響を受けずに撮影ができる
ビデオエフェクト>キーイング>ultraキー
キーカラー>画面の緑を選択
背景をシーケンスの下に配置
ウルトラキー>出力>アルファチャンネル
マットの生成 ハイライト・シャドウを調整 人物以外を真っ黒にする
コンポジットに戻す
マットのクリーンアップ>チョーク 縁を調整
不透明度>マスク 楕円>マスクの拡張 動画の縁を無視する
・VLOGをつくる
1)ヨリ・ヒキを意識した映像構成にする
飽きさせない 視聴維持率を上げること
2)音ハメ:BGMを入れたら、テンポに合わせてマーキングを入れる 動画の切り替えタイミングと合わせる
音源と菓子と動画との関連
歌詞付きの曲なら 歌詞の意味を調べてみよう
3)カラーグレーディング
カラーコレクション:カメラ違いの明るみを揃える
カラーグレーディング:色の差をつける(色の演出)
Lumetri カラー コントラスト 色かぶり補正 シャドウ
davinchi resolve 操作性がよい カラーグレーディング特化型のソフト(プレミアプロでもできるがダヴィンチのほうが優れている)
LUT設定:カラーグレーディングを簡単にできる機能 設定を購入することもできる
4)ライトリーク:lightleak
storybloksというサイトで背景映像をダウンロード 月額年間課金性
ライトリーク画像を、元映像の上に乗せる
元映像が見えないので不透明にする
不透明度>描画モード>スクリーンに変更
5)ビネット
元映像の上に調整レイヤー
mumetriカラー>ビネット 適用量 左:シックに 右:明るく
6)レターボックス
元映像の上に調整レイヤー
ビデオエフェクト> lgnite -generate >letterbox
上下に黒い縁ができる
一眼レフで撮影素材の世界観が整っている場合はレターボックス不要
でない場合は使えば簡単にかっこよくなる ボケ感が弱いiphonとか
方法1)ペンツール>長方形>で黒い帯を上乗せする方法 原始的
方法2)letter box pngで素材をダウンロード