前提・実現したいこと
敵を向いている方向にrigidbody動かしたい
発生している問題・エラーメッセージ
行って欲しくないところに行ってしまったり
敵が重なってしまう
該当のソースコード
unity
1ソースコード 2public class GoblinNomal : MonoBehaviour 3{ 4 5 public Animator animator; 6 private GameObject nearObj; 7 private Transform player; 8 int maxHp = 100; 9 int currentHp; 10 public Slider hpslider; 11 private GameObject damagemonsterUI; 12 int damage; 13 private float speed; 14 private float fleez; 15 private float span; 16 17 // Start is called before the first frame update 18 void Start() 19 { 20 animator = this.gameObject.GetComponent<Animator>();// 21 hpslider.value = 1; 22 currentHp = maxHp; 23 speed = 2; 24 span = 4; 25 damagemonsterUI = (GameObject)Resources.Load("System/DamageMonsterUI"); 26 } 27 28 // Update is called once per frame 29 void Update() 30 { 31 //最も近かったオブジェクトを取得 32 nearObj = GameObject.FindGameObjectWithTag("Player"); 33 player = nearObj.transform; 34 if (nearObj) 35 { 36 Quaternion lookRotation = Quaternion.LookRotation(nearObj.transform.position - transform.position, Vector3.up); 37 38 lookRotation.z = 0; 39 lookRotation.x = 0; 40 41 transform.rotation = Quaternion.Lerp(transform.rotation, lookRotation, 0.1f); 42 } 43 hpslider.value = currentHp / (float)maxHp; 44 if (currentHp <= 0) 45 { 46 Destroy(this.gameObject); 47 } 48 49 float dist = Vector3.Distance(player.position, transform.position); 50 51 if (dist <= 0.75f) 52 { 53 fleez += Time.deltaTime; 54 55 if (span < fleez) 56 { 57 animator.SetBool("attack01", true); 58 speed = 0; 59 fleez = 0; 60 } 61 else 62 { 63 animator.SetBool("attack01", false); 64 animator.SetBool("walk", false); 65 speed = 0; 66 } 67 } 68 else 69 { 70 speed = 2; 71 fleez = 4; 72////////////////////////////////////////////// 73 Vector3 velocity = gameObject.transform.rotation * new Vector3(0, 0, speed); 74 gameObject.transform.position += velocity * Time.deltaTime; 75//////////////////////////////// 76 animator.SetBool("walk", true); 77 animator.SetBool("attack01", false); 78 } 79 80 81 82 } 83 84 public void OnCollisionEnter(Collision collision) 85 { 86 var magicStatus = collision.gameObject.GetComponent<MagicStatus>(); 87 if (collision.gameObject.CompareTag("Magic")) 88 { 89 damage = magicStatus.damage; 90 if (magicStatus.attribute == Attribute.Normal) 91 { 92 currentHp -= damage; 93 animator.SetTrigger("Damage"); 94 } 95 else 96 { 97 animator.SetTrigger("EndDamage"); 98 } 99 100 if (magicStatus.attribute != Attribute.Normal) 101 { 102 currentHp -= damage; 103 animator.SetTrigger("Damage"); 104 } 105 else 106 { 107 animator.SetTrigger("EndDamage"); 108 } 109 damagemonsterUI.gameObject.GetComponentInChildren<Text>().text = "-" + damage; 110 Instantiate(damagemonsterUI, transform.position, Quaternion.identity); 111 } 112 } 113}
試したこと
//////で囲んでいる部分を似た様な質問であった
GetComponent<Rigidbody>().AddForce(transform.forward * 20, ForceMode.Force);
に変えてみたが動かなかった
敵が向いている方向というのは,spriteか何かでそのキャラが向いている方向ということでしょうか.
回答1件
あなたの回答
tips
プレビュー