c#游戏开发实战一-------角色移动脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class runing : MonoBehaviour
{
private Animator animationer;
private Rigidbody2D HeroRd;
private Transform HeroRd1;
private Collider2D Coll2d;
public float MoveSpeed;
public float JumpHeight;
int count=0;
public LayerMask Ground;
float h;
float v;
bool push;
bool push_s;
bool runing_jump;
public void sit(){
if(push_s==true)
{
animationer.SetBool("Walk",false);
animationer.SetBool("Sit",true);
if(Input.GetKey(KeyCode.A)||Input.GetKey(KeyCode.D))
{
animationer.SetBool("Crawl",true);
if(Input.GetKey(KeyCode.A))
{
HeroRd.velocity = new Vector2(h * MoveSpeed, HeroRd.velocity.y);
HeroRd1.localScale=new Vector3(-1,1,1);
}
else if(Input.GetKey(KeyCode.D))
{
HeroRd.velocity = new Vector2(h * MoveSpeed, HeroRd.velocity.y);
HeroRd1.localScale=new Vector3(1,1,1);
}
}
else
animationer.SetBool("Crawl",false);
}
else
{
animationer.SetBool("Sit",false);
animationer.SetBool("Crawl",false);
}
}
public void jump(){
if (Input.GetKeyDown(KeyCode.Space)&&Coll2d.IsTouchingLayers(Ground))
{
animationer.SetBool("Run",false);
animationer.SetTrigger("Jump");
HeroRd.AddForce(new Vector2(0, JumpHeight*3/2));
}
else if(Coll2d.IsTouchingLayers(Ground))
animationer.SetBool("Idle",true);
else
animationer.SetBool("Idle",false);
}
public void attack(){
if(Input.GetKeyDown(KeyCode.J))
{
animationer.SetTrigger("Attack");
}
}
public void run(){
if(Input.GetKey(KeyCode.A)&&push==true)
{
HeroRd.velocity = new Vector2(h * MoveSpeed*2, HeroRd.velocity.y);
HeroRd1.localScale=new Vector3(-1,1,1);
animationer.SetBool("Run",true);
}
else if(Input.GetKey(KeyCode.A))
{
HeroRd.velocity = new Vector2(h * MoveSpeed, HeroRd.velocity.y);
HeroRd1.localScale=new Vector3(-1,1,1);
animationer.SetBool("Walk",true);
animationer.SetBool("Run",false);
}
if(Input.GetKey(KeyCode.D)&&push==true)
{
HeroRd.velocity = new Vector2(h * MoveSpeed*2, HeroRd.velocity.y);
HeroRd1.localScale=new Vector3(1,1,1);
animationer.SetBool("Run",true);
}
else if(Input.GetKey(KeyCode.D))
{
HeroRd.velocity = new Vector2(h * MoveSpeed, HeroRd.velocity.y);
HeroRd1.localScale=new Vector3(1,1,1);
animationer.SetBool("Walk",true);
animationer.SetBool("Run",false);
}
else if(h==0)
{
animationer.SetBool("Walk",false);
animationer.SetBool("Run",false);
}
}
void Awake()
{
HeroRd = transform.GetComponent<Rigidbody2D>();
Coll2d=transform.GetComponent<Collider2D>();
HeroRd1 = transform.GetComponent<Transform>();
animationer = transform.GetComponent<Animator>();
}
void Update()
{
h = Input.GetAxis("Horizontal");
v=Input.GetAxis("Vertical");
attack();
if(Input.GetKey(KeyCode.LeftShift))
push=true;
else
push=false;
if(Input.GetKey(KeyCode.S))
push_s=true;
else
push_s=false;
if (Coll2d.IsTouchingLayers(Ground))
runing_jump=false;
else
runing_jump=true;
if(push_s==false&&Coll2d.IsTouchingLayers(Ground))
{
run();
}
else{
animationer.SetBool("Walk",false);
animationer.SetBool("Run",false);
}
jump();
sit();
}
}