- Home /
Duplicate Question
Help with Slender Pick Up Pages Script?
I have this script, and I'm trying to make a slender game, but when I go to pick up a page, nothing happens. #pragma strict
var papers : int = 0;
var papersToWin : int = 8;
var distanceToPaper : float = 2.5;
//public var paperpickup : AudioClip;
function Start()
{
Screen.lockCursor = true;
}
function Update()
{
if ( Input.GetMouseButtonUp(0) )
{
var ray = Camera.main.ScreenPointToRay( Input.mousePosition );
var hit : RaycastHit;
if ( Physics.Raycast( ray, hit, distanceToPaper ) )
{
if ( hit.collider.gameObject.name == "Paper" )
{
papers += 1;
//audio.PlayOneShot(paperpickup);
Debug.Log( "A paper was picked up. Total papers = " + papers );
Destroy( hit.collider.gameObject );
}
}
}
}
function OnGUI()
{
if ( papers < papersToWin )
{
GUI.Box( Rect( (Screen.width/2)-100, 10, 200, 35 ), "" + papers + " Papers" );
}
else
{
GUI.Box( Rect( (Screen.width/2)-100, 10, 200, 35 ), "All Papers Collected!" );
}
}
Any help? I'm pretty new to scripting, so I don't know what I did wrong. Also, all of my pages are named "Paper"
Did you follow the guide? : http://answers.unity3d.com/questions/321749/how-do-you-pick-up-pages-like-in-slender.html
What did you attach the script to? $$anonymous$$ake sure you follow the instructions properly, it is tested and working.
The only consideration may be that there is a chance that you are not close enough to the paper. The value of distanceToPaper is currently 2.5 units, make this about 4 or 5 (so you can see the paper, but not picking it up from the other side of the forest!). Add a Debug after the raycast to see if the raycast is hitting anything, and if so what is the name of the object the raycast is hitting :
if ( Physics.Raycast( ray, hit, distanceToPaper ) )
{
Debug.Log( "Raycast hit " + hit.collider.gameObject.name );
if ( hit.collider.gameObject.name == "Paper" )
{
Never $$anonymous$$d, I fixed it somehow, thanks for the help though!
I found out the problem people are having with pick-up-papers, it is when running in the editor and using Screen.lockCursor = true; , as soon as the mouse is clicked, the lock is broken, then the ray casts from the mouse pointer ins$$anonymous$$d of from the center of the screen. This can be worked around by changing 2 lines. On the collect paper script, add the E key so you don't use the mouse in the editor :
if ( Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.E) || Input.Get$$anonymous$$ouseButtonUp(0) )
the second line to change is straight after that one :
var ray = Camera.main.ScreenPointToRay( Vector3(Screen.width * 0.5, Screen.height * 0.5, 0) );
so the ray is cast from the center of the screen when the cursor is not locked. There seems to be interest in this so I'm working on a part 2 now, with fixes for people having problems with part 1 =]
here is a package of the project :
http://www.alucardj.net16.net/unityanswers/SlenderGuideV1-scene0.unitypackage
create a new project, then import the above asset. Open the folder _Scenes and then open scene0. Use the E key in the editor to pick up papers so that ScreenLock doesn't break, but hopefully adding the edits to the pick-up-paper script will make it work if ScreenLock breaks =]
Answer by AlucardJay · Nov 10, 2012 at 01:22 PM
Slender Guide Version 2
While I have finished writing the code, I don't have time to write a full guide explaining the steps taken and what I have coded in. I am changing the code in the below guide so people can still make their own rather than just using my package, and I really hope people write their own instead of just using my package.
Slender Guide Version 2 (I can only upload 5MB, so the project is very basic, but working!) : http://www.alucardj.net16.net/unityanswers/SlenderGuideV2-scene0.unitypackage
Fixed problems from Version 1 :
picking up papers in the editor - there were some issues with using LockCursor while running in the editor, hopefully these have been compensated for, recommend use the E key to pick up papers while running in the editor (but mouse still works). some movement issues - I had no problem, but it was brought up so I have tweaked the movement script.
New features :
The more papers picked up, the Man follows closer. Audio : when picking up paper, when the Man is first sighted, running and walking footsteps with adjustable audio gap between steps. Custom mesh with fading alpha fullscreen static effect.
And don't forget the awesome original flickering flashlight!
Here is the video link for the obstacle avoidance raycast : http://vimeo.com/9304844
Comments and feedback are welcome, as long as you have something more to say than just it doesn't work. The package proves it does. And please don't ask new questions, post comments here. If this keeps going or more people have requests, I might have to start a Unity Forum page.
Enjoy =]
How to make a 'Slender' game by Jay Kay (alucardj)
1- Create the terrain, and add a first person controller
there are many tutorials on both these topics, here are some quick links :
video : http://cgcookie.com/unity/2011/12/05/introduction-to-character-controllers/
written : http://wiki.unity3d.com/index.php?title=Terrain_tutorial
Some assets to help you out :
http://unity3d.com/support/resources/assets/terrain-assets
http://u3d.as/content/stormwater/heightfield-pack/2Q4
http://unity3d.com/support/resources/unity-extensions/terrain-toolkit
Also find some buildings (old shed, abandoned shack, etc) and anything you want to help the player use as 'landmarks' while searching around the terrain.
When you add a First Person Character Controller, Change the name of First Person Controller to Player.
2- Set the Ambience and Add a Flashlight
Here I am assuming you have created a terrain, added trees grass and buildings, and dropped in a first person character controller. Hopefully you have also pressed play and walked around the world you have created.
To give the scene a more 'spooky' feel, set the render settings.
In Unity, navigate to Edit > Render Settings
Enable (tick) the box that says Fog.
Click the Fog Colour box, set the ambient light to 29 on each of the RGB sliders. You can see the change in the scene, pick a colour that is dark but not pitch-black.
Click the Ambient Light Colour box, set the ambient light to 51 on each of the RGB sliders. You can see the change in the scene. Again, pick a colour that is dark but not pitch-black.
For a skybox I used the Moonshine skybox from the Standard Assets. (Assets > Import Package > Skyboxes). Drop Moonshine Skybox into Skybox Material (while in the Render Settings).
Now for the flashlight. Create a SpotLight, make it a child of the camera (so wherever the camera looks, the spotlight points). Set its Transform to X = 0; Y = 0.467; Z = 0; leave Rotations at 0, Scale at 1.
My settings for the spotlight are :
Range = 25; Spot Angle = 71.5870; Color I made very slightly yellow; Intensity = 1.85;
Now when you press play, you should be walking around your dark scene with a torchlight effect in front of where you look.
Advancing : I helped someone with a flickering flashlight, and have adapted that script to have the following behaviour. 1- light works for 1-2 minutes. 2- Light starts to flicker. 3- press F to reset light (light flashes twice as if being tapped/shaken) then light works again for another 1-2 minutes. I think it works well to add suspense (the flashlight suddenly flickers, and you have to reset it) . The link is : http://answers.unity3d.com/questions/316189/i-want-to-turn-my-flashlight-on-and-off-while-stil.html#answer-316302
3- How to Pick Up Papers
This one gets asked alot, and the usual response is a trigger-collider setup. For this tutorial, I am going to use a raycast method.
First create some papers. This part is easy =] Create a cube, scale it to X = 0.6; Y = 0.9; Z = 0.01;
Name it Paper. Now Duplicate it 7 times, so you have 8 Paper cubes total.
There are some images that can be found on page 5 of this thread : http://forum.unity3d.com/threads/134862-Slender-Man-Design-Outline
Create a material for each Paper, then apply them to the cubes. You can place these where you want around the scene, just make sure they are set at a realistic height, and preferably so they can only seen from one side (nailed to a thick tree, on the side of a shed).
Now to make it so these papers can be collected.
Create a new script, call it CollectPapers. Attach it to the Player. Here is the code :
#pragma strict
@script RequireComponent( AudioSource )
var papers : int = 0;
var papersToWin : int = 8;
var distanceToPaper : float = 2.5;
public var paperPickup : AudioClip;
var theEnemy : EnemyScript;
function Start()
{
Screen.lockCursor = true;
// find and store a reference to the enemy script (to reduce distance after each paper is collected)
if ( theEnemy == null )
{
theEnemy = GameObject.Find( "Enemy" ).GetComponent( EnemyScript );
}
}
function Update()
{
//if ( Input.GetMouseButtonUp(0) ) // use E in editor as LockCursor breaks with left mouseclick
if ( Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.E) )
{
//var ray = Camera.main.ScreenPointToRay( Input.mousePosition ); // always cast ray from center of screen
var ray = Camera.main.ScreenPointToRay( Vector3( Screen.width * 0.5, Screen.height * 0.5, 0.0 ) );
var hit : RaycastHit;
if ( Physics.Raycast( ray, hit, distanceToPaper ) )
{
//if ( hit.collider.gameObject.tag == "Paper" )
if ( hit.collider.gameObject.name == "Paper" )
{
papers += 1;
//Debug.Log( "A paper was picked up. Total papers = " + papers );
audio.PlayClipAtPoint( paperPickup, transform.position );
Destroy( hit.collider.gameObject );
// make enemy follow closer
theEnemy.ReduceDistance();
}
}
}
}
function OnGUI()
{
if ( papers < papersToWin )
{
GUI.Box( Rect( (Screen.width * 0.5) - 60, 10, 120, 25 ), "" + papers.ToString() + " Papers" );
}
else
{
GUI.Box( Rect( (Screen.width/2)-100, 10, 200, 35 ), "All Papers Collected!" );
// Application.LoadLevel( "sceneWin" );
}
}
NOTE : in the Start function, there is the line Screen.lockCursor = true; this is to hide the cursor and lock it to the center of the screen. This can have some silly effects when you run in the editor and then click the mouse, but in a build you notice it works as expected. (this script is adapted from my answer here : http://answers.unity3d.com/questions/239927/Collecting-Papers-and-Keeping-Track-of-how-many-collected--need-help.html)
So, when the left mouse button is released, a ray is cast for a certain distance. If the player is close enough to something named Paper, and the ray hits Paper, then the count is increased and the Paper is destroyed.
At this stage you should be walking around your 'spooky' scene, collecting papers with the amount collected displayed at the top.
Advancing : I found this link for when the paper is found, first displaying the paper full-screen, then destroying the paper. I think that effect would be cool but havn't looked into it yet. The link is : http://answers.unity3d.com/questions/15438/trying-to-pick-up-and-see-paper-pop-up-gui-window.html
4- How to Have an Enemy Follow the Player at a Distance
If you were observant, you would have noticed a model where you got the images for the papers! You can use this, but as the 'man' always looks at the player, a 2D image can be used. Search for an image you want to use (), then make a material for that image. (http://forums.d2jsp.org/topic.php?t=64345908&f=202, http://www.zerochan.net/1271218, etc)
Create a Cube, name it Enemy, scale it to X = 1; Y = 2; Z = 0.1;
Remove or replace the Box Collider with a Capsule Collider ( Component > Physics > Capsule Collider ). My settings for the Capsule Collider are Center = 0 for XYZ, Radius = 0.5, Height = 1, Direction = Y-Axis.
Now also attach a Rigidbody Component ( Component > Physics > Rigidbody ). My settings for the Rigidbody are Mass = 1; Use Gravity = true.
Now for the script, create and call it EnemyScript. I have seen many answers use the Render.isVisible method. For this I am using a Dot.Product method. First there is a check if in a Dot.Product greater than 0.8, then check if within the maximum viewable distance, then check if there is a direct line-of-sight to the player (i.e. not occluded/behind a tree or building). Here is the code :
#pragma strict
@script RequireComponent( AudioSource )
public var thePlayer : Transform;
private var theEnemy : Transform;
public var speed : float = 5.0;
var isOffScreen : boolean = false;
public var offscreenDotRange : float = 0.7;
var isVisible : boolean = false;
public var visibleDotRange : float = 0.8; // ** between 0.75 and 0.85 (originally 0.8172719)
var isInRange : boolean = false;
public var followDistance : float = 24.0;
public var maxVisibleDistance : float = 25.0;
public var reduceDistAmt : float = 3.1;
private var sqrDist : float = 0.0;
public var health : float = 100.0;
public var damage : float = 20.0;
public var enemySightedSFX : AudioClip;
private var hasPlayedSeenSound : boolean = false;
private var colDist : float = 5.0; // raycast distance in front of enemy when checking for obstacles
function Start()
{
if ( thePlayer == null )
{
thePlayer = GameObject.Find( "Player" ).transform;
}
theEnemy = transform;
}
function Update()
{
// Movement : check if out-of-view, then move
CheckIfOffScreen();
// if is Off Screen, move
if ( isOffScreen )
{
MoveEnemy();
// restore health
RestoreHealth();
}
else
{
// check if Player is seen
CheckIfVisible();
if ( isVisible )
{
// deduct health
DeductHealth();
// stop moving
StopEnemy();
// play sound only when the Man is first sighted
if ( !hasPlayedSeenSound )
{
audio.PlayClipAtPoint( enemySightedSFX, thePlayer.position );
}
hasPlayedSeenSound = true; // sound has now played
}
else
{
// check max range
CheckMaxVisibleRange();
// if far away then move, else stop
if ( !isInRange )
{
MoveEnemy();
}
else
{
StopEnemy();
}
// reset hasPlayedSeenSound for next time isVisible first occurs
hasPlayedSeenSound = false;
}
}
}
function DeductHealth()
{
// deduct health
health -= damage * Time.deltaTime;
// check if no health left
if ( health <= 0.0 )
{
health = 0.0;
Debug.Log( "YOU ARE OUT OF HEALTH !" );
// Restart game here!
// Application.LoadLevel( "sceneLose" );
}
}
function RestoreHealth()
{
// deduct health
health += damage * Time.deltaTime;
// check if no health left
if ( health >= 100.0 )
{
health = 100.0;
//Debug.Log( "HEALTH is FULL" );
}
}
function CheckIfOffScreen()
{
var fwd : Vector3 = thePlayer.forward.normalized;
var other : Vector3 = (theEnemy.position - thePlayer.position).normalized;
var theProduct : float = Vector3.Dot( fwd, other );
if ( theProduct < offscreenDotRange )
{
isOffScreen = true;
}
else
{
isOffScreen = false;
}
}
function MoveEnemy()
{
// Check the Follow Distance
CheckDistance();
// if not too close, move
if ( !isInRange )
{
rigidbody.velocity = Vector3( 0, rigidbody.velocity.y, 0 ); // maintain gravity
// --
// Old Movement
//transform.LookAt( thePlayer );
//transform.position += transform.forward * speed * Time.deltaTime;
// --
// New Movement - with obstacle avoidance
var dir : Vector3 = ( thePlayer.position - theEnemy.position ).normalized;
var hit : RaycastHit;
if ( Physics.Raycast( theEnemy.position, theEnemy.forward, hit, colDist ) )
{
//Debug.Log( " obstacle ray hit " + hit.collider.gameObject.name );
if ( hit.collider.gameObject.name != "Player" && hit.collider.gameObject.name != "Terrain" )
{
dir += hit.normal * 20;
}
}
var rot : Quaternion = Quaternion.LookRotation( dir );
theEnemy.rotation = Quaternion.Slerp( theEnemy.rotation, rot, Time.deltaTime );
theEnemy.position += theEnemy.forward * speed * Time.deltaTime;
// --
}
else
{
StopEnemy();
}
}
function StopEnemy()
{
transform.LookAt( thePlayer );
rigidbody.velocity = Vector3.zero;
}
function CheckIfVisible()
{
var fwd : Vector3 = thePlayer.forward.normalized;
var other : Vector3 = ( theEnemy.position - thePlayer.position ).normalized;
var theProduct : float = Vector3.Dot( fwd, other );
if ( theProduct > visibleDotRange )
{
// Check the Max Distance
CheckMaxVisibleRange();
if ( isInRange )
{
// Linecast to check for occlusion
var hit : RaycastHit;
if ( Physics.Linecast( theEnemy.position + (Vector3.up * 1.75) + theEnemy.forward, thePlayer.position, hit ) )
{
Debug.Log( "Enemy sees " + hit.collider.gameObject.name );
if ( hit.collider.gameObject.name == "Player" )
{
isVisible = true;
}
}
}
else
{
isVisible = false;
}
}
else
{
isVisible = false;
}
}
function CheckDistance()
{
var sqrDist : float = (theEnemy.position - thePlayer.position).sqrMagnitude;
var sqrFollowDist : float = followDistance * followDistance;
if ( sqrDist < sqrFollowDist )
{
isInRange = true;
}
else
{
isInRange = false;
}
}
function ReduceDistance()
{
followDistance -= reduceDistAmt;
}
function CheckMaxVisibleRange()
{
var sqrDist : float = (theEnemy.position - thePlayer.position).sqrMagnitude;
var sqrMaxDist : float = maxVisibleDistance * maxVisibleDistance;
if ( sqrDist < sqrMaxDist )
{
isInRange = true;
}
else
{
isInRange = false;
}
}
function OnGUI()
{
GUI.Box( Rect( (Screen.width * 0.5) - 60, Screen.height - 35, 120, 25 ), "Health : " + parseInt( health ).ToString() );
}
5- Play and Test your Game =]
If all has gone well, you now have your very own Slender game !
This is just the start, try adding many more things :
Add Sounds !! Batteries to pick up for the Flashlight when it runs out of charge. Full screen display of the page when collected. A Game Over screen and a way to restart the game.
Hope you have found this useful and helpful =]
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Vehicle Script Debugging 1 Answer
Need a bit of help with my script (about 100 lines) 1 Answer
How to make the trigger work only once. (SOUND) 1 Answer
Score System help 1 Answer