iLMS知識社群歷程檔Login
Position: 黃國哲 > Unity
1100108 新控制人物腳本
by 黃國哲 2021-01-08 16:21:37, Reply(0), Views(69)

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

public class PlayerMovement : MonoBehaviour {

public GameObject hitParticle;
private float speed = 5f;
float shootTimer = 0;

private Rigidbody rb;
private AudioSource shootSound;

void Start () {
Application.targetFrameRate = 300;
shootSound = GameObject.Find("ShotSound").GetComponent<AudioSource> ();
rb = GetComponent<Rigidbody> ();
}
void FixedUpdate () {
Vector3 moveX = JoystickLeft.positionX * speed * transform.right;
Vector3 moveY = JoystickLeft.positionY * speed * transform.forward;
rb.MovePosition(transform.position + moveX * Time.fixedDeltaTime + moveY  * Time.fixedDeltaTime);

//transform.position = transform.position + moveX * Time.fixedDeltaTime + moveY  * Time.fixedDeltaTime; If your character doesn't have rigidbody you can use this
}

void Update() {
transform.rotation = Quaternion.Euler(JoystickRight.rotY, JoystickRight.rotX, 0);

shootTimer += Time.deltaTime;
if(JoystickRight.shot) {
if(shootTimer >= 0.2f) {
shootTimer = 0;
shootSound.Play();
ShootBullets();
}
}
}

private void ShootBullets() {
RaycastHit hit;
if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit)) {
GameObject particle = Instantiate(hitParticle, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(particle, 0.5f);
}
}

public void Jump() {
if(JoystickRight.jump) {
JoystickRight.jump = false;
GetComponent<Rigidbody> ().AddForce(new Vector3(0, 500, 0));
}
}

void OnTriggerEnter(Collider col) {
JoystickRight.jump = true;
}

}


//////////////////以下為Joystick腳本


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Settings : MonoBehaviour {

public GameObject LeftStickMovementTrashold;
public GameObject LeftSticky;
public GameObject LeftMoveBaseOnDrag;

public void RestartScene() {
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}

public void LeftStickySettings (){
JoystickLeft jl = GameObject.Find("Joystick").GetComponent<JoystickLeft> ();
if(LeftSticky.GetComponent<Toggle>().isOn) {
jl.sticky = true;
jl.Init();
}else {
jl.sticky = false;
jl.Init();
}
}

public void LeftMoveBaseOnDragSettings (){
JoystickLeft jl = GameObject.Find("Joystick").GetComponent<JoystickLeft> ();
if(LeftMoveBaseOnDrag.GetComponent<Toggle>().isOn) {
jl.moveJoystickBaseOnDrag = true;
jl.Init();
}else {
jl.moveJoystickBaseOnDrag = false;
jl.Init();
}
}

public void LeftStickMovementTrasholdSettings (){
JoystickLeft jl = GameObject.Find("Joystick").GetComponent<JoystickLeft> ();
jl.stickMovementThreshold = (int)LeftStickMovementTrashold.GetComponent<Slider>().value;
jl.Init();
}

}

Reply