iLMS知識社群歷程檔登入
位置: 黃國哲 > Unity
1090404 清明節成果
by 黃國哲 2020-04-04 20:53:38, 回應(0), 人氣(416)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
public class playercontrler : MonoBehaviour
{

    public float speed = 0.1f ;
    public float high = 1 ;
    //public Rigidbody2D rigid2D ; 暫時不用
    Rigidbody2D rigid2D ;
    public float speed_x_constraint ;
    // Start is called before the first frame update
    void Start()
    {
        print("start");
        rigid2D=this.gameObject.GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update() 
    {
    print(rigid2D.velocity);
    // 向右移動0.1F
    if (Input.GetKey(KeyCode.RightArrow))
    {
     rigid2D.AddForce(new Vector2(50,0),ForceMode2D.Force);
    //this.gameObject.transform.position += new Vector3(speed,0,0);
    } 
    // 向左移動0.1F
    if (Input.GetKey(KeyCode.LeftArrow))
    {this.gameObject.transform.position -= new Vector3(speed,0,0);
    } 
    // 向上跳躍
    if (Input.GetKey(KeyCode.Space))
    {rigid2D.AddForce(new Vector3(0,high,0),ForceMode2D.Impulse);
     print("jump");
    }
    //constraint
    if(rigid2D.velocity.x>speed_x_constraint)
    {
    rigid2D.velocity= new Vector2 (speed_x_constraint.rigid2D.velocity.y);
    }
     if(rigid2D.velocity.x< -speed_x_constraint)
    {
    rigid2D.velocity= new Vector2 (speed_x_constraint.rigid2D.velocity.y);
    }


    }
}


Unity in C# (Button Script)

回應