LoginSignup
dddddddddddd
@dddddddddddd (陸 加治屋)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

unityでスクリプトを組んでキャラにアタッチしたがキャラが思った通りに動かない

解決したいこと

pcで作って十字キーで試してます
よくあるアクションゲームみたいにカメラの正面方向に対して画面の右側に動いたり後ろに動かしたりその方向に向かってオブジェクト自身も回転する処理がしたいんですがキーを押すとその場でコマみたいに回りだして歩き出してくれないんです

該当するソースコード c#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NejikoController : MonoBehaviour
{
    CharacterController controller;
    Animator animator;
    Vector3 moveDirection = Vector3.zero;

    public float gravity;
    public float speed;
    public float speedJump;
    public GameObject camobj;

    void Start()
    {
        
        //移動方向をローカルからワールド空間に変換する
        animator = GetComponent<Animator>();
    }


    void Update()
    {
       CharacterController controller = GetComponent<CharacterController>();
        if (controller.isGrounded)
        {
           

            //入力値にカメラのオイラー角を掛ける事で、カメラの角度に応じた移動方向に補正する
            moveDirection = Quaternion.Euler(0, camobj.transform.localEulerAngles.y, 0) * new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
             //移動方向をローカルからワールド空間に変換する
            moveDirection = transform.TransformDirection(moveDirection);

            moveDirection *= speed;

            if (Input.GetButton("Jump"))
                {
                    moveDirection.y = speedJump;
                    animator.SetTrigger("jump");
                }
          
        }

         transform.rotation = Quaternion.LookRotation(new Vector3(moveDirection.x, 0, moveDirection.z));

        
        moveDirection.y -= gravity * Time.deltaTime;

        controller.Move(moveDirection * Time.deltaTime);
        if (controller.isGrounded)
        {
            moveDirection.y = 0;
 
        }
        animator.SetBool("run", moveDirection.z != 0.0f || moveDirection.x != 0.0f);
    }

自分で試したこと

ここに問題・エラーに対して試したことを記載してください。

0

1Answer

まずはキー入力とかカメラは無視して「時間とともにキャラがどんどん前に進むだけのスクリプト」
それとは別に「時間とともにキャラがその場で回転するだけのスクリプト」
を作ってみてはどうでしょうか。

もたいぶって答えを教えようとしないわけではなく、上に書いたような基本は押さえておかないと今後も思い通りにいかないことばかりになりそうな予感がするので…

0

Your answer might help someone💌